在QML中布局分为以下几种:绝对坐标、锚布局、定位器、布局管理器。
设置x、y、width、height能够定位一个组件的位置,这种方法扩展性太差。
Button{width: 50height: 50x: 10y:10background: Rectangle{color:"red"}}
示例:实现一行按钮。
Window {id: windowobjectName: "window"visible: truewidth: 400height: 500title: qsTr("Hello World")//做一行按钮Button{id:b1width: 50height: 50anchors.centerIn: parent //在Window的中心background: Rectangle{color:"red"}}Button{id:b2width: 50height: 50anchors.left: b1.right //b2放在b1的右边,左边距20anchors.top: b1.topanchors.leftMargin: 20background: Rectangle{color:"black"}}Button{id:b3width: 50height: 50anchors.right: b1.left //b3放在b1的左边,右边距20anchors.top: b1.topanchors.rightMargin: 20background: Rectangle{color:"blue"}}Button{id:b4width: 25 //b4放在b1的中心height: 25anchors.horizontalCenter: b1.horizontalCenteranchors.verticalCenter: b1.verticalCenterbackground: Rectangle{color:"yellow"}}}
Row和Column差不多
Window {id: windowobjectName: "window"visible: truewidth: 400height: 500title: qsTr("Hello World")Rectangle{border.color: "black"border.width: 2width: 200height: 300Row {Repeater {model: 3Button {width: 30height: 40background: Rectangle{color:"yellow"}text:index}}spacing: 10 //设置间隔padding: 10 //设置内边距}}
}
Flow:流式布局
示例:Flow项自动将子Text项并排放置,当超出父控件边界时会自动换行。
Window {id: windowobjectName: "window"visible: truewidth: 400height: 500title: qsTr("Hello World")Rectangle{border.color: "black"border.width: 2width: 200height: 300Flow {anchors.fill: parentanchors.margins: 4spacing: 10Text { text: "Text"; font.pixelSize: 40 }Text { text: "items"; font.pixelSize: 40 }Text { text: "flowing"; font.pixelSize: 40 }Text { text: "inside"; font.pixelSize: 40 }Text { text: "a"; font.pixelSize: 40 }Text { text: "Flow"; font.pixelSize: 40 }Text { text: "item"; font.pixelSize: 40 }}}
}
Grid:网格布局
可以控制绘制几行几列。
Window {id: windowobjectName: "window"visible: truewidth: 400height: 500title: qsTr("Hello World")Rectangle{border.color: "black"border.width: 2width: 200height: 300Grid {columns: 3spacing: 2padding: 10Rectangle { color: "red"; width: 50; height: 50 }Rectangle { color: "green"; width: 20; height: 50 }Rectangle { color: "blue"; width: 50; height: 20 }Rectangle { color: "cyan"; width: 50; height: 50 }Rectangle { color: "magenta"; width: 10; height: 10 }}}
}
有很多附加属性。
Window {id: windowobjectName: "window"visible: truewidth: 400height: 500title: qsTr("Hello World")RowLayout {id: layoutanchors.fill: parentspacing: 6Rectangle {color: 'teal'Layout.fillWidth: trueLayout.minimumWidth: 50Layout.preferredWidth: 100Layout.maximumWidth: 300Layout.minimumHeight: 150Text {anchors.centerIn: parenttext: parent.width + 'x' + parent.height}}Rectangle {color: 'plum'Layout.fillWidth: trueLayout.minimumWidth: 100Layout.preferredWidth: 200Layout.preferredHeight: 100Text {anchors.centerIn: parenttext: parent.width + 'x' + parent.height}}}
}