目录
布局元素
QML 使用 anchors
(锚)对元素进行布局。anchoring
(锚定)是基础元素对象的基本属性,可以被所有的可视化 QML 元素使用。
一个 anchors
(锚)就像一个协议,并且比几何变化更加强大。Anchors
(锚)是相对关系的表达式,通常需要与其它元素搭配使用。
一个元素有6条锚定线:
-
top
(顶) -
bottom
(底) -
left
(左) -
right
(右) -
horizontalCenter
(水平中) -
verticalCenter
(垂直中)
在文本元素中有一条文本的锚定文本基线 baseline
。
每一条锚定线都有一个偏移 offset
值,在顶,底,左,右的锚定线中它们也被称作边距。对于水平中与垂直中与文本基线中被称作偏移值。
定义组件 GreenSquare
:
// GreenSquare.qml
import QtQuick 2.0
Rectangle {
width: 100
height: 100
color: "#7FB937"
border.color: Qt.lighter(color)
}
布局:
// Anchors.qml
import QtQuick 2.2
import QtQuick.Window 2.2
Window{
height: 600;width: 800
Grid
{
spacing: 10
rows: 2
columns: 3
GreenSquare {
BlueSquare {
width: 12
anchors.fill: parent
anchors.margins: 8
Text {
anchors.centerIn: parent
text: qsTr("(1)")
}
}
}
GreenSquare {
BlueSquare {
width: 48
y: 8
anchors.left: parent.left
anchors.leftMargin: 8
Text {
anchors.centerIn: parent
text: qsTr("(2)")
}
}
}
GreenSquare {
BlueSquare {
width: 48
anchors.left: parent.right
Text {
anchors.centerIn: parent
text: qsTr("(3)")
}
}
}
GreenSquare {
BlueSquare {
id: blue1
width: 48; height: 24
y: 8
anchors.horizontalCenter: parent.horizontalCenter
}
BlueSquare {
id: blue2
width: 72; height: 24
anchors.top: blue1.bottom
anchors.topMargin: 4
anchors.horizontalCenter: blue1.horizontalCenter
Text {
anchors.centerIn: parent
text: qsTr("(3)")
}
}
}
GreenSquare {
BlueSquare {
width: 48
anchors.centerIn: parent
Text {
anchors.centerIn: parent
text: qsTr("(3)")
}
}
}
GreenSquare {
BlueSquare {
width: 48
anchors.horizontalCenter: parent.horizontalCenter
anchors.horizontalCenterOffset: -12
anchors.verticalCenter: parent.verticalCenter
Text {
anchors.centerIn: parent
text: qsTr("(3)")
}
}
}
}
}
运行: