基于锚(anchors)的布局
QtQuick还提供了一种使用锚(anchors)的概念来进行项目布局的方法。每一个项目都可以认为有一组无形的“锚线”:left、horizontalCenter、right、top、verticalCenter、baseline和bottom,图中没有显示baseline,它是一条假想的线,文本坐落在这条线上。对于没有文本的项目,它与top相同。对于本节的内容,大家可以在Qt帮助中通过Positioning with Anchors关键字查看。
Rectangle {
id: rect1
width: 50; height: 50; color: "blue"
}
Rectangle {
id: rect2
width: 50; height: 50; color: " red"
// rect2左边的对齐rect1的右边
anchors.left: rect1.right
}
使用anchors.fill等价于设置left、right、top和bottom 锚定到目标项目的left、right、top和bottom;anchors.centerIn等价于设置verticalCenter和 horizontalCenter锚定到目标项目的 verticalCenter和horizontalCenter等。
锚边距和偏移
锚定系统也允许为一个项目的锚指定边距(margin)和偏移(offset)。边距指定了项目锚到外边界的空间量,而偏移则允许使用中心锚线进行定位。一个项目可以通过leftMargin、rightMargin、topMargin和bottomMargin独立指定锚边距;也可以使用 anchor.margins来为所有的4个边指定相同的边距。锚偏移可以使用horizontalCenterOffset、verticalCenterOffset和 baselineOffset来指定。
Rectangle {
id: rect1
width: 50; height: 50; color: "blue"
}
Rectangle {
id: rect2
width: 50; height: 50; color: " red"
// rect2左边的对齐rect1的右边
anchors.left: rect1.right
// 5像素的边距
anchors.leftmargin: 5
}
运行时改变锚
Qt Quick 提供了AnchorChanges类型,以便在运行时修改项目的锚,它需要在状态State中进行。AnchorChanges不能修改项目的边距,需要时可以使用PropertyChanges完成。
Rectangle {
id: win
width: 120; height: 120
color: "black"
Rectangle { id: myRect; width: 50; height: 50; color: "red"}
states: State {
name: "reanchored"
AnchorChanges {
target: myRect
anchors.top: win.top
anchors.bottom: win.bottom
}
PropertyChanges {
target: myRect
anchors.topMargin: 10
anchors.bottomMargin: 10
}
}
MouseArea {
anchors.fill: parent;
onClicked: win.state = "reanchored"
}
}