布局管理器
QtQuick布局管理器(Layouts)是一组在用户界面中用于排列项目的类型。
与定位器不同,布局管理器不仅进行布局,而且会改变项目的大小,所以更适用于需要改变用户界面大小的应用。
因为布局管理器也继承自Item
,所以她们可以嵌套。
QtQuick布局管理器类似于传统 Qt Widgets应用的布局管理器。使用时需要导入:import QtQuick.Layouts
布局管理器主要包括:
RowLayout
ColumnLayout
GridLayout
StackLayout
见Qt帮助文档:Qt Quick Layouts Overview
1. 主要特色
- 项目的对齐方式由
Layout.alignment
指定,主要有:Qt::AlignLeft
Qt::AlignHCenter
Qt::AlignRight
Qt::AlignTop
Qt::AlignVCenter
Qt::AlignBottom
Qt:AlignBaseline
- 可变大小的项目使用
Layout.fillWidth
和Layout.fillHeight
属性指定,当将其值设为true
时会根据约束条件变宽或变高。 - 大小约束可以通过
Layout.minimumWidth
、Layout.preferedWidth
和Layout.maximumWidth
(包括height对应的)来指定。 - 间距可以通过
spacing
、rowSpacing
和columnSpacing
属性指定。
除了上面的,GridLayout
还有如下特色:
- 网格中的坐标可以通过
Layout.row
和Layout.column
指定。 - 自动网格坐标同时使用了
flow
、rows
、column
属性。 - 行或列的跨度可以通过
Layout.rowSpan
和Layout.columnSpan
属性来指定。
2. 大小约束
要想使得一个项目可以通过布局管理器调整大小,需要指定其:
- 最小宽高(
minimumWidth
,MinimumHeight
) - 最佳宽高(
preferedWidth
,preferedWidth
) - 最大宽高(
maximumWidth
,maximumHeight
)
并将对应的Layout.fillWidth
或Layout.fillHeight
设置为true。
例:
在一个布局管理器中横向排列两个矩形,当拉伸程序窗口时,左边距形可以从50x150变化到300x150,右边矩形可以从100x150变化到∞x100
import QtQuick
import QtQuick.Layouts
Window{
width: 400
height: 300
visible: true
RowLayout{
id: layout
anchors.fill: parent
spacing: 6
Rectangle{
color: "lightgrey"
Layout.fillWidth: true
Layout.minimumWidth: 50
Layout.preferredWidth: 100
Layout.maximumWidth: 300
Layout.minimumHeight: 150
Text {
anchors.centerIn: parent
text: parent.width + 'x' + parent.height
}
}
Rectangle{
color: "black"
Layout.fillWidth: true
Layout.minimumWidth: 100
Layout.preferredWidth: 200
Layout.preferredHeight: 100
Text {
anchors.centerIn: parent
text: parent.width + 'x' + parent.height
color: "white"
}
}
}
}
有效的最佳(preferred)属性值可能来自几个候选属性。要决定有效的最佳属性,会对这些候选属性以下面的顺序进行查询,使用第一个有效的值:
Layout.preferredWidth
或Layout.preferredHeight
implicitWidht
或implicitHeight
width
或height
一个项目可以仅指定Layout.preferredWidth
而不指定Layout.preferredHeight
,此时,有效的最佳高度会从implicitHeight
或最终的height
中选取。
为了将布局管理器与窗口进行关联,可以为布局管理器添加锚anchors.fill
,确保布局管理器能够跟随窗口一起改变大小。
布局管理器的大小约束可以用来确保窗口大小不会超过约束条件,还可以将布局管理器的约束设置到窗口项目的minimumWidth
、minimumHeight
、maximumWidth
和maximumHeight
等属性。
例如下面的代码:
Window{
width: 400
height: 300
visible: true
minimumWidth: layout.Layout.minimumWidth
minimumHeight: layout.Layout.minimumHeight
maximumWidth: 1000
maximumHeight: layout.Layout.maximumHeight
RowLayout{
...
}
}
实际编程中,通常希望窗口的初始化大小可以是布局管理器的隐含(implicit)大小,那么就可以这样来设置:
Window{
width: layout.implicitWidth
height: layout.implicitHeight
RowLayout{ ... }
}
3. StackLayout
StackLayout栈布局管理器可以管理多个项目,但是只能显示一个项目。
可以通过currentIndex
属性来设置当前显示的项目,索引号对应布局管理器中子项目的顺序,从0开始。
另外,StackLayout还包含index和isCurrentItem
等附加属性。
例如:
import QtQuick
import QtQuick.Layouts
Window{
width: 640
height: 480
visible: true
StackLayout{
id:layout
anchors.fill: parent
currentIndex: 1
Rectangle{
color: "plum"
implicitWidth: 300
implicitHeight: 200
}
}
MouseArea{
anchors.fill: parent
onClicked: {
if(layout.currentIndex === 1)
layout.currentIndex = 0;
else
layout.currentIndex = 1
}
}
}