本节介绍QML的页面布局和基础控件。
垂直布局,会将内部嵌套的元素自动排成一列
ColumnLayout{ spacing: 2 Rectangle { id:rect1 width: 100 height: 100 x:100 y:100 border.color: "black" border.width: 5 radius: 5 gradient: Gradient{ GradientStop{position: 0.0;color: "lightsteelblue"} GradientStop{position: 1.0;color: "red"} } } Rectangle { id:rect2 width: 100 height: 100 border.color: "black" border.width: 5 radius: 5 gradient: Gradient{ GradientStop{position: 0.0;color: "lightsteelblue"} GradientStop{position: 1.0;color: "blue"} } } }水平布局,会将内部嵌套的元素自动排成一行
RowLayout{ spacing = 20 Rectangle{ ... } Rectangle{ ... } }栅格布局,设置行数,列数
Grid{ spacing: 2 rows: 2 columns: 2 Rectangle{...} Rectangle{...} Rectangle{...} Rectangle{...} }组件是用于规模化输出相同的元素,可以在一个QML文件中,也可以引用另外一个QML作为组件
通过独立的QML文件编写我们常用的组件
// Mysec.qml Item { property Component myRecComponet: myRec Component{ id:myRec Rectangle{ width: 100 height: 100 x:100 y:100 border.color: "white" border.width: 2 radius: 5 gradient: Gradient{ GradientStop{position: 0.0;color: "lightsteelblue"} GradientStop{position: 1.0;color: "blue"} } } } } // main.qml ListView{ width: 600 height: 600 model: 4 //定义list元素个数 delegate:myrec.myRecComponet //代理,引用组件 MyRec{id:myrec} }文本标签,继承了字体的样式
Label{ text: "hello world" font.pixelSize: 20 font.italic: true }可以进行编辑的文本框
ColumnLayout{ spacing: 5 anchors.centerIn: parent TextInput{ width: 60 height: 20 focus: true text: "请输入A" } TextInput{ width: 60 height: 20 text: "请输入B" } }下拉框,点击下拉按钮,显示所有选项
ComboBox { model: ["First", "Second", "Third"] }Context Menu:右键点击固定区域,弹出菜单
Rectangle{ width: 120 height: 40 anchors.centerIn: parent border.color: "black" border.width: 2 Text{ anchors.centerIn: parent text: "right click" font.family: "ubuntu" } MouseArea { anchors.fill: parent acceptedButtons: Qt.RightButton onClicked: { if (mouse.button === Qt.RightButton) contextMenu.popup() //菜单弹出 } Menu { id: contextMenu MenuItem { text: "Cut" } MenuItem { text: "Copy" } MenuItem { text: "Paste" } } } }Button Menu:点击按钮,弹出菜单
Button { id: fileButton text: "文件" onClicked: menu.open() anchors.centerIn: parent Menu { id: menu y: fileButton.height MenuItem { text: "新建" } MenuItem { text: "打开" } MenuItem { text: "保存" } } }