基于锚的布局
每一个项目都可以认为有一组无形的锚线:
- left
- hoizontalCenter
- right
- top
- verticalCenter
- baseline
- bottom
其中baseline是一条假想的线,文本坐落在这条线上。
对于没有文本的项目,baseline与top相同。
见Qt帮助:Positioning with Anchors
1. 使用锚布局
7条锚线分别对应了Item
项目中的anchors
属性组的相关属性。因为Qt Quick中所有可视项目都继承自Item
,所以所有可视项目都可以使用锚进行布局。
Qt Quick锚定系统允许不同项目的锚线之间建立关系
import QtQuick
Item{
width: 250
height: 150
Rectangle{
id: rect1; x: 10; y: 20
width: 100
height: 100
color: "lightgrey"
Text {
text: "rect1"
anchors.centerIn: parent
}
}
Rectangle{
id: rect2
width: 100
height: 100
color: "black"
anchors.left: rect1.right
Text {
text: "rect2"
color: "white"
anchors.centerIn: parent
}
}
}
将rect2
的左边界锚定到了rect1
的右边界。
还可以指定多个锚,例如:
import QtQuick
Item{
width: 250
height: 150
Rectangle{
id: rect1; x: 10; y: 20
width: 100
height: 100
color: "lightgrey"
Text {
text: "rect1"
anchors.centerIn: parent
}
}
Rectangle{
id: rect2
width: 100
height: 100
color: "black"
anchors.left: rect1.right
anchors.top: rect1.bottom
Text {
text: "rect2"
color: "white"
anchors.centerIn: parent
}
}
}
透过指定多个水平、垂直的锚,可以控制一个项目的大小,例如:
import QtQuick
Item{
width: 250
height: 150
Rectangle{
id: rect1; x: 10; y: 20
width: 100
height: 100
color: "lightgrey"
Text {
text: "rect1"
anchors.centerIn: parent
}
}
Rectangle{
id: rect2
width: 100
height: 100
color: "black"
anchors.left: rect1.right
anchors.right: rect3.left
anchors.top: rect1.top
Text {
text: "rect2"
color: "white"
anchors.centerIn: parent
}
}
Rectangle{
id: rect3
width: 100
height: 100
color: "green"
x: 150
Text {
text: "rect3"
anchors.centerIn: parent
}
}
}
2. 锚边距和偏移
锚定系统也允许为一个项目的锚指定边距(margin)和偏移(offset)。
边距指定了项目锚到外边界的空间量,偏移则允许使用中心锚线进行定位。
锚边距属性:
leftMargin
rightMargin
topMargin
bottomMargin
margin
(同时指定4个边距)
锚偏移属性:
horizontalCenterOffser
verticalCenterOffset
baselineOffset
3. 运行时改变锚
Qt Quick提供了AnchorChanged
类型,以便在运行时修改项目的锚,它需要在状态State
中进行。
AnchorsChanged
不能修改项目的边距,需要时可以使用PropertyChangeds
完成.
另外,还可以使用AnchorAnimation
类型来提供动画效果。
例子(使用AnchorChanged
改变了项目的top
和bottom
锚,使用PropertyChangeds
修改top
和bottom
锚边距):
import QtQuick
Rectangle{
id: window
width: 150
height: 200
color: "lightgrey"
Rectangle{ id:myRect; width: 100; height: 100; color: "black" }
states: State{
name: "reanchored"
AnchorChanges{
target: myRect
anchors.top: window.top
anchors.bottom: window.bottom
}
PropertyChanges {
target: myRect
anchors.topMargin: 10
anchors.bottomMargin: 10
}
}
transitions: Transition {
AnchorAnimation {duration: 1000}
}
MouseArea{
anchors.fill: parent
onClicked: window.state = "reanchored"
}
}
另外,还可以通过JavaScript改变锚,但是一定要注意操作的顺序,否则可能出现奇怪的结果。
例如:
Rectangle{
width: 50
anchors.left: parent.left
function reanchorToRight(){
anchors.left = undefined
anchors.right = parent.left
}
}
如果更换两行代码的位置,就可能出现不同的结果:
anchors.right = parent.right
anchors.left = undefined