在 QML 中创建 Hide/Flex 个项目

Make Hide/Flex Items in QML

有没有办法使用 QML 复制您在这个人的 中看到的这种 hide/flex 效果?我还使用 QT Creator 来帮助 UI 构建,所以在我下面使用的基线示例中,我有一个按钮,当按下该按钮时,将显示一个白色矩形,其中将包含更多内容它在未来。而当这个白色长方形出现的时候,白色长方形里面的灰色长方形也随之变长,基本上把它包起来了。在此过程中,Some 文本也像 after.png 一样被向下推。再次按下按钮时,白色矩形应该消失,Some 文本应该移回上层。

除了使用 hide 来编写部分功能外,我不知道如何让对象像那样移动。这是对应于 after.png

的代码
import QtQuick 2.4
import QtQuick.Controls 2.12

Item {
    id: item1
    width: 800
    height: 600

    Page {
        anchors.fill: parent

        Rectangle {
            id: bound
            color: "#cad2d7"
            anchors.fill: parent
            anchors.bottomMargin: 0

            Button {
                id: button
                x: 8
                y: 8
                text: qsTr("Button")
            }

            Rectangle {
                id: rectangle
                x: 0
                y: 74
                width: 800
                height: 200
                color: "#ffffff"
            }

            Text {
                id: text1
                x: 14
                y: 293
                text: qsTr("Some text")
                font.pixelSize: 60
            }
        }
    }
}

我也在使用 Python (PySide6),但不确定是否必须编写某种控制器来控制元素。 after.png before.png(请注意,您在 before.png 中看到的白色只是白色背景)

您似乎在寻找类似 accordion design pattern 的内容,您可以在其中展开以显示通常不可见的内容。在您描述的场景中,一种简单的方法是在灰色底色 Rectangle 中添加 ColumnLayout,其中切换中间内容的可见性。这是一个完整的独立示例:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12

Window {
    width: 640
    height: 480
    visible: true

    Rectangle {
        color: "lightgrey"
        width: parent.width
        height: column.implicitHeight // note this rectangle derives its height from column, and column derives its height from its children's implicitHeight or Layout.prefererredHeight

        ColumnLayout {
            id: column
            width: parent.width
            spacing: 0

            Button {
                text: qsTr("Button")
                onClicked: {
                    middleRectangle.visible = !middleRectangle.visible // toggle middleRectangle visibility
                }
            }

            Rectangle {
                id: middleRectangle
                Layout.fillWidth: true
                Layout.preferredHeight: 100
                visible: false  // note default is NOT visible

                Text {
                    text: qsTr("New text")
                    font.pixelSize: 60
                }
            }

            Text {
                text: qsTr("Some text")
                font.pixelSize: 60
            }
        }
    }
}

需要注意的事项是:

  • visible: false 的项目不会在 ColumnLayout/RowLayout 中占用 space,但是,不同的定位器并非如此 ColumnRow
  • 包含所有内容的基础 Rectangle 的高度来自 ColumnLayout,而 ColumnLayout 的高度又来自其子项
  • 您提到的 似乎不符合您的描述设计,因此这种方法不一定适用于该场景,但它的某些部分会起作用,例如切换可见性。