Mat*_*nik 2 user-interface qt qml qt-quick qtquickcontrols
我想创建一个类似手风琴的动画元素,单击时会展开。这是它应该如何工作的。
当用户单击红色矩形之一时,作为实际内容的绿色矩形应该展开。我希望这个扩展是动画的。每个红色标题的绿色矩形内容的高度可能不同。
我已经能够实现点击展开行为,但没有动画。这是我目前拥有的代码。
AccordionElement.qml
import QtQuick 2.5
import QtQuick.Layouts 1.1
ColumnLayout {
id: rootElement
property string title: ""
property bool isOpen: false
default property alias accordionContent: contentPlaceholder.data
anchors.left: parent.left; anchors.right: parent.right
// Header element
Rectangle {
id: accordionHeader
color: "red"
anchors.left: parent.left; anchors.right: parent.right
height: 50
MouseArea {
anchors.fill: parent
Text {
text: rootElement.title
anchors.centerIn: parent
}
cursorShape: Qt.PointingHandCursor
onClicked: {
rootElement.isOpen = !rootElement.isOpen
}
}
}
// This will get filled with the content
ColumnLayout {
id: contentPlaceholder
visible: rootElement.isOpen
anchors.left: parent.left; anchors.right: parent.right
}
}
Run Code Online (Sandbox Code Playgroud)
这就是它在父元素中的使用方式:
Accordion.qml
ColumnLayout {
Layout.margins: 5
visible: true
AccordionElement {
title: "Title1"
accordionContent: Rectangle {
anchors.left: parent.left; anchors.right: parent.right
height: 20
color: "green"
}
}
AccordionElement {
title: "Title2"
accordionContent: Rectangle {
anchors.left: parent.left; anchors.right: parent.right
height: 50
color: "green"
}
}
AccordionElement {
title: "Title3"
accordionContent: Rectangle {
anchors.left: parent.left; anchors.right: parent.right
height: 30
color: "green"
}
}
// Vertical spacer to keep the rectangles in upper part of column
Item {
Layout.fillHeight: true
}
}
Run Code Online (Sandbox Code Playgroud)
这会产生以下结果(当所有矩形都展开时):
理想情况下,我希望绿色矩形从红色矩形中滚出(就像打印机中的纸张一样)。但我对如何做到这一点感到困惑。我已经尝试了几种使用该height属性的方法,并且我让绿色矩形消失,但白色空间仍然保留在红色矩形下方。
任何帮助,将不胜感激。我缺少一种方法吗?
这是一个快速而简单的示例:
// AccItem.qml
Column {
default property alias item: ld.sourceComponent
Rectangle {
width: 200
height: 50
color: "red"
MouseArea {
anchors.fill: parent
onClicked: info.show = !info.show
}
}
Rectangle {
id: info
width: 200
height: show ? ld.height : 0
property bool show : false
color: "green"
clip: true
Loader {
id: ld
y: info.height - height
anchors.horizontalCenter: info.horizontalCenter
}
Behavior on height {
NumberAnimation { duration: 200; easing.type: Easing.InOutQuad }
}
}
}
// Acc.qml
Column {
spacing: 5
AccItem {
Rectangle {
width: 50
height: 50
radius: 50
color: "blue"
anchors.centerIn: parent
}
}
AccItem {
Rectangle {
width: 100
height: 100
radius: 50
color: "yellow"
anchors.centerIn: parent
}
}
AccItem {
Rectangle {
width: 75
height: 75
radius: 50
color: "cyan"
anchors.centerIn: parent
}
}
}
Run Code Online (Sandbox Code Playgroud)
您不必要地使锚点和布局变得过于复杂。问题似乎并不需要这些。
更新:我稍微改进了实现,与最初的实现相比,内容实际上会像纸张从打印机中滑出一样从标题中滑出,而不是简单地被揭开,并且还消除了误报绑定循环警告的来源。