在 Qt Widgets 中,我们经常使用布局管理器来管理界面上的众多 widgets 。在 Qt Quick 中其实有两套与布局管理相关的类库,一套叫作 Item Positioner ,一套叫作 Item Layout 。 Item Layout 包括 RowLayout 、 ColumnLayout 、 GridLayout,与 Qt Widgets 中的布局管理器更相近,不过这里不打算介绍它们,本文的重点是 Item Positioner 。 Qt Quick 提供这么几种常用的 Positioners :
- anchors ,锚布局
- Row ,行布局
- Column ,列布局
- Grid ,表格布局
- Flow ,流式布局
咱们一个一个来看。
请给我的决赛文章《Qt Quick 图像处理实例之美图秀秀(附源码下载)》投票,谢谢。
版权所有 foruok ,转载请注明出处:http://blog.csdn.net/foruok 。
anchors(锚)布局
在《Qt on Android: Qt Quick 简单教程》一文中我们已经介绍过锚布局了。为了自成篇幅,这里再重复一下,不过示例会更新哦。
anchors 提供了一种方式,让你可以通过指定一个元素与其它元素的关系来确定元素在界面中的位置。
你可以想象一下,每个 item 都有 7 条不可见的锚线:左(left)、水平中心(horizontalCenter)、上(top)、下(bottom)、右(right)、垂直中心(verticalCenter)、基线(baseline)。看图 1 就明白了:
图 1 锚线
在图 1 中,没有标注基线,基线是用于定位文本的,你可以想象一行文字端坐基线的情景。对于没有文本的图元,baseline 和 top 一致。
使用 anchors 布局时,除了对齐锚线,还可以在指定上(topMargin)、下(bottomMargin)、左(leftMargin)、右(rightMargin)四个边的留白。看图 2 就明白了:
图 2 留白
除了图 1 和图 2 介绍的属性, anchors 还有一些属性, centerIn 表示将一个 item 居中放置到另一个 item 内, fill 表示充满某个 item ……更多请参考 Item 类的文档。
好了,基础知识介绍完毕,看一个大而全的例子,文件名是 anchors_layout.qml ,内容如下:
import QtQuick 2.0
import QtQuick.Controls 1.1
Rectangle {
width: 360;
height: 240;
color: "#EEEEEE";
id: rootItem;
Text {
id: centerText;
text: "A Single Text.";
anchors.centerIn: parent;
font.pixelSize: 24;
font.bold: true;
}
function setTextColor(clr){
centerText.color = clr;
}
//color pickers look at parent's top
ColorPicker {
id: topColor1;
color: Qt.rgba(Math.random(), Math.random(), Math.random(), 1.0);
anchors.left: parent.left;
anchors.leftMargin: 4;
anchors.top: parent.top;
anchors.topMargin: 4;
onColorPicked: setTextColor(clr);
}
ColorPicker {
id: topColor2;
color: Qt.rgba(Math.random(), Math.random(), Math.random(), 1.0);
anchors.left: topColor1.right;
anchors.leftMargin: 4;
anchors.top: topColor1.top;
onColorPicked: setTextColor(clr);
}
ColorPicker {
id: topColor3;
color: Qt.rgba(Math.random(), Math.random(), Math.random(), 1.0);
anchors.right: parent.right;
anchors.rightMargin: 4;
anchors.top: parent.top;
anchors.topMargin: 4;
onColorPicked: setTextColor(clr);
}
ColorPicker {
id: topColor4;
color: Qt.rgba(Math.random(), Math.random(), Math.random(), 1.0);
anchors.right: topColor3.left;
anchors.rightMargin: 4;
anchors.top: topColor3.top;
onColorPicked: setTextColor(clr);
}
//color pickers sit on parent's bottom
ColorPicker {
id: bottomColor1;
color: Qt.