一.前言
先前了解了QML的添加控件与绑定信号槽,那么控件的摆放就是一个问题,虽然可以手动去设置控件的位置,但是有些时候还是需要自动对齐啥的,这时候就需要用到布局,该篇文章先简单了解QML提供的布局方式,后续再做深入研究
二.QML布局方式
1.行布局(Row)
import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 2.1
Window{
visible: true
width: 640
height: 480
title: qsTr("网格布局举例")
// 行布局
Rectangle{
x:50
y:200
id:row_rect
width: 200
height: 100
border.color: "green"
radius: 15
Row{
spacing: 5 // 设置行与行之间的间距
anchors.centerIn: parent // 相对于父窗口居中
Rectangle { color: "red"; width: 50; height: 50 }
Rectangle { color: "green"; width: 50; height: 50 }
Rectangle { color: "blue"; width: 50; height: 50 }
}
}
}
2.列布局(Column)
// 列布局
Rectangle{
x:300
y:200
id:column_rect
width: 200
height: 300
border.color: "green"
radius: 15
Column{
spacing: 5 // 设置列与列之间的间距
anchors.centerIn: parent // 相对于父窗口居中
Rectangle { color: "red"; width: 50; height: 50 }
Rectangle { color: "green"; width: 50; height: 50 }
Rectangle { color: "blue"; width: 50; height: 50 }
}
}
3.网格布局(Grid)
// 网格布局
Rectangle{
x:300
y:200
id:gird_rect
width: 200
height: 200
border.color: "green"
radius: 15
Grid{
spacing: 5
columns: 3
anchors.centerIn: parent // 相对于父窗口居中
// 会根据设置的列数自动换行
Rectangle { color: "red"; width: 50; height: 50 }
Rectangle { color: "green"; width: 50; height: 50 }
Rectangle { color: "blue"; width: 50; height: 50 }
Rectangle { color: "black"; width: 50; height: 50 }
Rectangle { color: "#125636"; width: 50; height: 50 }
Rectangle { color: "gray"; width: 50; height: 50 }
Rectangle { color: "#148936"; width: 50; height: 50 }
}
}
4.流方布局(Flow)
Window{
visible: true
width: 200
height: 200
title: qsTr("QML布局方式")
Flow {
anchors.fill: parent
anchors.margins: 4
spacing: 10
Rectangle { color: "red"; width: 50; height: 50 }
Rectangle { color: "green"; width: 50; height: 50 }
Rectangle { color: "blue"; width: 50; height: 50 }
Rectangle { color: "black"; width: 50; height: 50 }
Rectangle { color: "#125636"; width: 50; height: 50 }
Rectangle { color: "gray"; width: 50; height: 50 }
Rectangle { color: "#148936"; width: 50; height: 50 }
Rectangle { color: "#789632"; width: 50; height: 50 }
Rectangle { color: "#223366"; width: 50; height: 50 }
}
}