|本文大概阅读时间5分钟。
|版权说明:原创文章,如需转载,请标明文章出处。https://blog.csdn.net/weixin_40192195/article/details/109205056
目录
一.前言
本节介绍QML的页面布局和基础控件。
1.Layout(布局)
1)ColumnLayout(垂直布局)
垂直布局,会将内部嵌套的元素自动排成一列
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"}
}
}
}
2)RowLayout(行布局)
水平布局,会将内部嵌套的元素自动排成一行
RowLayout{
spacing = 20
Rectangle{
...
}
Rectangle{
...
}
}
3)Grid(栅格布局)
栅格布局,设置行数,列数
Grid{
spacing: 2
rows: 2
columns: 2
Rectangle{...}
Rectangle{...}
Rectangle{...}
Rectangle{...}
}
2.Component(组件)
组件是用于规模化输出相同的元素,可以在一个QML文件中,也可以引用另外一个QML作为组件
1)当前文件内
Item {
width: 600; height: 600
Component {
id: redSquare
Rectangle {
id:rect4
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"}
}
}
}
Loader { sourceComponent: redSquare } // 调用组件
Loader { sourceComponent: redSquare; x: 100 }
Loader { sourceComponent: redSquare; x: 200 }
}
2)自定义组件
通过独立的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}
}
3.Control(基础控件)
1)Lable(标签)
文本标签,继承了字体的样式
Label{
text: "hello world"
font.pixelSize: 20
font.italic: true
}
2)TextInput(文本输入框)
可以进行编辑的文本框
ColumnLayout{
spacing: 5
anchors.centerIn: parent
TextInput{
width: 60
height: 20
focus: true
text: "请输入A"
}
TextInput{
width: 60
height: 20
text: "请输入B"
}
}
3)ComboBox(下拉框)
下拉框,点击下拉按钮,显示所有选项
ComboBox {
model: ["First", "Second", "Third"]
}
4)Menu(菜单)
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: "保存"
}
}
}