锚(anchors)布局,每一个项目都可以认为有一组无形的锚线
left,horizontalCenter,right,top,verticalCenter,baseline和bottom.
如上图:图中没有显示baseline,它是一条假想的线,文本坐落在这条线上。对于没有文本的项目它与top相同。
- 使用锚布局
7条锚分别对应了Item项目中的anchors属性组的相关属性。因为Qt Quick中所有可视项目都继承自Item,所以所有可视项目都可以使用锚进行布局。Qt Quick的锚定系统允许不同项目的锚线之间建立关系。
import QtQuick 2.2
Item {
Rectangle {
id: rect1
width: 50; height: 50; color: "blue"
}
Rectangle {
id: rect2
width: 50; height: 50; color: "red"
anchors.left: rect1.right
}
}
- 这里rect2的左边界锚定到了rect1的右边界。
- 另外还可以指定多个锚。
Rectangle { id: rect1; .... }
Rectangle {
id: rect2;
anchors.left; rect1.right; anchors.rop; rect1.bottom; ...
}
通过指定多个水平或者垂直的锚可以控制一个项目的大小:
例如:rect2锚定到了rect1的右边和rect3的左边,当rect1或rect3移动时,rect2会进行必要的伸缩或收缩。
Rectangle { id: rect1; x: 0; ... }
Rectangle { id: rect2; anchors.left: rect1.right; anchors.right: rect3.left; ... }
Rectangle { id: rect3; x: 150; ... }
Qt Quick 还提供了一系列方便使用的锚。例如,使用anchors.fill等价于设置left,right,top和bottom锚定到目标项目的left,right,top和bottom; anchors.centerIn等价于设置verticalCenter和horizontalCenter锚定到目标项目的verticalCenter 和 horizontalCenter等。
- 锚边距和位移
锚定系统也允许为一个项目的锚指定边距(margin)和偏移量(offset)。 边距指定了项目锚到外边界的空间量,而偏移则允许使用中心锚线进行定位。一个项目可以通过leftMargin,rigtMargin,topMargin和bottomMargin独立指定锚边距。
如图所示:也可以使用anchor.margins来为所有的4个边指定相同的边距。锚偏移可以使用
horizontalCenterOffset,verticalCenterOffset 和 baselineOffset来指定。
- 例如下面代码片段中,在rect2的左边留有5像素的边距。运行效果示意图:
import QtQuick 2.0
Item {
Rectangle { id: rect1; width: 50; height: 50; color: "blue" }
Rectangle {
id: rect2;
width: 50; height: 50;
color: "red"
anchors.left: rect1.right;
anchors.leftMargin: 5;
}
}
- 运行时改变锚
Qt Quick 提供了AnchorChanges类型,以便在运行时修改项目的锚,它需要在状态State中进行。AnchorChanges不能修改项目的边距,需要时可以使用PropertyChanges完成。
例子:使用AnchorChanges改变了项目的top和bottom锚,使用PropertyChanges修改了top和bottom锚边距。
import QtQuick 2.2
Rectangle {
id: window
width: 120; height: 120
color: "black"
Rectangle { id: myRect; width: 50; height: 50; color: "red" }
states: State {
name: "reanchored"
AnchorChanges {
target: myRect
anchors.top: window.top
anchors.bottom: window.bottom
}
PropertyChanges {
target: myRect
anchors.topMargin: 10
anchors.bottomMargin: 10
}
}
MouseArea {
anchors.fill: parent;
onClicked: window.state = "reanchored"
}
}