Qml中实现可伸展布局

公司的项目中需要用Qt写一个桌面软件,因为C++还不很熟悉,因此用QML来写界面。不过相关的资料比较少。除了官方文档基本上找不到第三方控件。

今天要实现的是一个点击伸展和收缩的控件,找了一遍没找到相关的实现,只能自己写了。

原理

自定义一个Item,包裹一个按钮和一个扩展区。点击按钮的时候伸展和收缩扩展区的高度, 并在高度变化的时候添加一个动画效果。实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//FileName: ExpandableLayout.qml
Rectangle {
property alias title: draw_title.text
property alias frame: loader.sourceComponent
property int frameHeight: 120
height: draw_title.height + loader.height

Button {
id: draw_title
onClicked: {loader.height = loader.height === 1? frameHeight: 1}
}

Loader {
anchors.top: draw_title.bottom
width: draw_title.width
height: 1
id: loader

Behavior on height {
NumberAnimation { duration: 300; easing.type: Easing.OutBack }
}
}
}

使用

1
2
3
4
5
6
7
ExpandableLayout {
title: "点我"
frameHeight: 90
frame: Rectangle {
color: "red"
}
}

听说,赞赏了的人都变美了哦~
0%