前言
在使用QML编写代码时,经常会搞混几种水平,垂直居中的写法,以下是个人做的一点笔记
一、父子,同级组件之间,使用锚定(anchors)
锚定(anchors)在确定父子组件之间,同级组件之间的相对位置时非常常用,若使用锚定方式确定子组件与父组件之间的位置关系,使用 top,bottom,left,right, topMargin,bottomMargin,leftMargin,rightMargin进行上下左右对齐,以及对齐后的留白距离。若要使子组件在父组件的水平,垂直居中,使用:
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
当然,若需要使子组件在父组件中央,可更为简单的使用:
anchors.centerIn: parent
二、Layout内的组件之间
若使用Layout包裹组件,希望组件之间能对齐,使用Layout.alignment属性,类型为枚举,共有7个值
Qt::AlignLeft
Qt::AlignHCenter
Qt::AlignRight
Qt::AlignTop
Qt::AlignVCenter
Qt::AlignBottom
Qt::AlignBaseline
如,有一个Label和一个ComboBox水平布置,希望Label和ComboBox的水平线居中对齐,使用 Layout.alignment: Qt.AlignHCenter:
RowLayout {
anchors.left: parent.left
anchors.leftMargin: 30
anchors.verticalCenter: parent.verticalCenter
spacing: 10
Label {
Layout.preferredWidth: 100
Layout.alignment: Qt.AlignHCenter
text: qsTr("筛选条件: ")
}
ComboBox {
Layout.preferredWidth: 180
Layout.preferredHeight: 40
Layout.alignment: Qt.AlignHCenter
model: [qsTr("老师"), qsTr("学生"), qsTr("全部")]
}
}
三、Label,Text,TextFiled等组件的内容
对Label,Text,TextFiled等组件的内容位置,使用horizontalAlignment,verticalAlignment,其类型为枚举,有3种方式供选择
// horizontalAlignment
TextInput.AlignLeft
TextInput.AlignRight
TextInput.AlignHCenter
// verticalAlignment
TextInput.AlignTop
TextInput.AlignBottom
TextInput.AlignVCenter (default).
例如一个TextField的文本居中,使用如下代码
TextField {
width: 160
height: 40
text: qsTr("文本居中")
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}