1. 布局简介
QT Quick编码实现界面布局一般有四种方式:
- 绝对坐标:x、y、z、width、height;
- 锚(anchors) 布局;
- 定位器(Row、Column、Grid、Flow);
- 布局管理器(GridLayout、RowLayout、ColumnLayout);
2. 区别
首先,Row和Column是QtQuick 库提供的,RowLayout以及ColumnLayout是QtQuick.Layouts提供的。顾名思义,含有Layout的表示一种布局方法,而Row和Column表示一种排列方法。
Column和ColumnLayout都是控制元素纵向排列的,不过Column是排列,layout是布局;column需要自己定义高,或者隐含高度, layout可以定义多种高度。包括最小,最大,合适,全覆盖等。
Column是用来控制列排列的,ColumnLayout实际效果是控制垂直方向布局的(行)。
定位器中的对象需要明确设定width和height。
3. 布局管理器的关键属性
布局管理器使用时,需要关注的属性如下:
- 可使用Layout.alignment属性指定项目的对齐方式;
- 可调整大小的Item可以使用Layout.fillWidth和Layout.fillHeight属性指定;
- 可使用Layout.minimumWidth,Layout.preferredWidth和Layout.maximumWidth属性指定width的限制;
- 可使用Layout.minimumHeight,Layout.preferredHeight和Layout.maximumHeight属性指定height的限制;
- 可以使用spacing,rowSpacing或columnSpacing来指定间距;
- 此外,GridLayout还添加了以下功能:
- 可以使用Layout.row和Layout.column属性确定Grid坐标;
- 自动Grid坐标和flow, rows, columns 参数一起使用;
- 可以使用Layout.rowSpan(Item所占行数)和Layout.columnSpan(Item所占列数)属性指定跨行或跨列的Item的跨度。
4. 布局管理器使用注意事项
布局管理器使用时,布局负责分配其子Items的几何形状, 因此不应指定子Items的width, height, x, y或其他任何可能影响布局的因素(如anchors等). 否则会产生冲突, 导致布局的结果具有不确定性.。
如果子Item也是布局, 也同样要遵循这个原理. 因此,只有没有父布局的布局才能具有“anchors.fill:parent;”。
示例代码如下:
import QtQuick 2.12
import QtQuick.Layouts 1.12
Rectangle {
id:container;
width: 320;
height: 240;
RowLayout {
anchors.fill: parent;
spacing: 6; // 布局中的所有Item之间的间距均为6像素
Rectangle {
color: "black";
Layout.preferredWidth: 100; // 建议宽度
//Layout.preferredHeight: 120; // 建议高度
Layout.fillHeight: true; // 占据为其分配的所有高度
}
Rectangle {
color: "plum";
Layout.fillWidth: true; // 占据为其分配的所有宽度
Layout.fillHeight: true; // 占据为其分配的所有高度
}
}
}
运行效果图如下:
拉伸窗口后效果如下:
4. 布局中Items的大小控制例子
代码如下:
import QtQuick 2.12
import QtQuick.Layouts 1.12
Rectangle {
id:container;
width: 320;
height: 240;
RowLayout {
id: _layout;
anchors.fill: parent;
spacing: 6;
Rectangle {
color: 'azure';
Layout.fillWidth: true;
Layout.minimumWidth: 50; // 最小宽度50
Layout.preferredWidth: 100; // 建议宽度100
Layout.maximumWidth: 300; // 最大宽度300
Layout.minimumHeight: 150; // 最小高度150
Text {
anchors.centerIn: parent;
text: parent.width + 'x' + parent.height;
}
}
Rectangle {
color: 'plum';
Layout.fillWidth: true;
Layout.minimumWidth: 100; // 最小宽度
Layout.preferredWidth: 200; // 建议宽度
Layout.preferredHeight: 100; // 建议高度
Text {
anchors.centerIn: parent;
text: parent.width + 'x' + parent.height;
}
}
}
}
运行效果如下:
刚运行窗口大小后效果如下: