QtQuick布局管理器是一组用于在用户界面中排列项目的类型。与前面讲到的定位器不同,布局管理器不仅进行布局,而且会改变项目的大小,所以更适用于需要改变用户界面大小的应用。因为布局管理器也是继承自Item,所以它们可以嵌套。Qt Quick布局管理器与传统QtWidgets应用中的布局管理器很相似。QtQuick布局管理器主要包括RowLayout、ColumnLayout和GridLayout。对于可以在Qt帮助中通过Qt Quick Layouts Overview关键字查看。
Qt Quick Layouts拥有下面几个主要特色:
要想使一个项目可以通过布局管理器调整大小,需要指定其最小宽高(minimumWidth和minimumHeight)、最佳宽高(preferredWidth和preferredHeight)和最大宽高(maximumWidth和maximumHeight),并将对应的Layout.fillWidth 或Layout.fillHeight设置为true。
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.1Item {RowLayout {id: layoutanchors.fill: parentspacing: 6Rectangle {color: 'green'Layout.fillWidth: trueLayout.minimumWidth: 50Layout.preferredWidth: 100Layout.maximumWidth: 300Layout.minimumHeight: 150Text {anchors.centerIn: parenttext:parent.width + 'x' + parent.height}}Rectangle {color: "red"Layout.fillWidth: trueLayout.minimumWidth: 100Layout.preferredWidth: 200Layout.preferredHeight: 100Text {anchors.centerIn: parenttext: parent.width + 'x' + parent.height}}}}
有效的最佳(preferred)属性的值,可能来自几个候选属性。要决定有效的最佳属
性,会对这些候选属性以下面的顺序进行查询,使用第一个有效的值。
LayoutMirroring附加属性用来在水平方向镜像项目锚布局、定位器(Row和Grid等)和视图(GridView和水平ListView等)。镜像只是视觉上的变化,例如左侧布局变成右侧布局。当在项目中将LayoutMirroring的enabled 属性设置为true时启用镜像,默认镜像只影响该项目本身。如果将childrenInherit属性设置为true,那么该项目
的所有子项目都会启用镜像。
下面的例子中,Row被锚定在了其父项目的左侧,然而,因为启用了镜像,锚在水
平方向进行了翻转,现在Row被锚定在了右侧。又因为Row中的子项目默认从左向
右排列,它们现在会从右向左排列。
Rectangle {LayoutMirroring.enabled: trueLayoutMirroring.childrenInherit: truewidth: 300; height: 50color: "yellow"border.width: 1Row {anchors { left: parent.left; margins: 5}y: 5; spacing: 5Repeater {model: 5Rectangle {color: "red"opacity: (5 - index)/5width: 40; height: 40Text {text: index + 1anchors.centerIn: parent}}}}}
布局镜像在需要同时支持从左到右和从右到左布局的应用中是很有用的。如果想了解更多关于从右到左用户界面的内容,可以在帮助中索引Right-to-left User Interfaces关键字。
下一篇:编写函数判断密码的有效性