QML元素布局(定位器、锚、绝对坐标)
QML中主要有3种元素布局方式:绝对坐标(包括关联坐标)、定位器(Poisitioners)、锚(Anchors)。
绝对坐标
给出元素的(x,y)坐标即可确定位置,但屏幕调整会导致问题出现。例:
width: 100
height: 200
定位器(Poisitioners)
定位器是QML专用于定位的一类元素,主要有Row(行)、Column(列)、Grid(网格)、Flow(流定位)。
其他.qml
import QtQuick 2.0
Rectangle {
width:64
height: 32
color: "red" //"blue"、"green"
border.color: Qt.lighter(color)
}
Row{} :
将被其定位的元素成员放在一行的位置,所有元素之间的间距相等,spacing来设置间距值,顶端保持对齐。
Column{}:
将元素成员按照加入的顺序,从上往下在同一列排开。
Grid{} :
将其元素成员排成一个网格,默认从左往右排列,每行4个元素,可用rows、columns来设置行和列的数值。
Flow{} :
将元素成员以流的方式显示出来,根据显示区域,动态调整布局方式。
main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
id: window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Flow{
anchors.fill: parent
spacing: 5
Red {}
Blue {}
Green{}
Red {}
Blue {}
Green{}
}
Row{
x:24
y:100
spacing: 2 //设置间距值
Red {}
Blue {}
Green{}
}
Column{
x:100
y:200
Red {}
Blue {}
Green{}
}
Grid{
x:100
y:350
columns: 2 //设置一行显示的元素个数
Red {}
Blue {}
Green{}
}
}
实现效果:
锚(Anchors)
每个元素都被认为有一组无形的“锚线”,其属性有
左(left),、右(right),
垂直中心(vertical center)、顶(top),
底(bottom) 、水平中心(horizontal center)。
此外,锚直接作用于父元素。
anchors.left: parent.right //与父元素窗口左锚线锚定
anchors.leftMargin: 5 //设定与窗口的左边距(leftMargin, rightMargin, topMargin 和 bottomMargin)
简单示例
Blue{
id:blue
anchors.left: parent.left
anchors.top: parent.top
anchors.leftMargin: 25
anchors.topMargin: 25
}
Green{
id :green
anchors.left:blue.left
anchors.top: blue.top
anchors.leftMargin: 25
anchors.topMargin: 25
}
实现效果: