一、概述
在QML中定位一个元素 Item 有好几种方法。这里的定位其实就是就是为了布局元素,布局元素有很多种方法,我一般使用的就是第五种 Layout Types,这种类型能够动态的适应窗口大小,同时也适合缩放的一些问题,这种布局在和普通Qt C++开发界面的方式很类似的,下面就介绍QML里面会用到的几种布局概述。
二、Manual Positioning 手动定位
手动定位布局,其实就是通过设置元素 Item 的x,y属性,可以将它们放置在屏幕上特定的x,y坐标处。根据视觉坐标系统规则,这将设置它们相对于其父元素左上角的位置。
结合使用绑定而不是这些属性的常量值,通过为适当的绑定设置x和y坐标也可以轻松地实现相对定位。
import QtQuick 2.3
Item {
width: 100; height: 100
Rectangle {
// Manually positioned at 20,20
x: 20
y: 20
width: 80
height: 80
color: "red"
}
}
三、Anchors 定位
基本上每个 可视化 Item 类型都提供了锚定到其他 Item 类型的能力。每个元素有7条锚线:左、右、垂直居中、上、下、基线和水平居中。这三条垂直锚线可以锚定到另一个项目的三条垂直锚线中的任何一条上,这四条水平锚线可以锚定到另一个项目的水平锚线上。Anchors 也是用的相对锚定的方式来实现的。
import QtQuick 2.3
Item {
width: 200; height: 200
Rectangle {
// Anchored to 20px off the top right corner of the parent
anchors.right: parent.right
anchors.top: parent.top
anchors.margins: 20 // Sets all margins at once
width: 80
height: 80
color: "orange"
}
Rectangle {
// Anchored to 20px off the top center corner of the parent.
// Notice the different group property syntax for 'anchors' compared to
// the previous Rectangle. Both are valid.
anchors {
horizontalCenter: parent.horizontalCenter; top: parent.top; topMargin: 20 }
width: 80
height: 80
color: "green"
}
}
四、Positioners 定位器
对于想要在常规模式中定位一组类型的常见情况,Qt Quick提供了一些定位器类型。放置在定位器中的物品会以某种方式自动定位;例如,一行将元素定位为水平相邻(形成一行)。这个和布局器里面的布局很相似。
import QtQuick 2.3
Item {
width: 300; height: 100
Row {
// The "Row" type lays out its child items in a horizontal line
spacing: 20 // Places 20px of space between items
Rectangle {
width: 80; height: 80; color: "red" }
Rectangle {
width: 80; height: 80; color: "green" }
Rectangle {
width: 80; height: 80; color: "blue" }
}
}
五、Layout Types 布局类型
Layout Types 类型的作用方式与定位器类似,但 Layout Types 的功能更加强大,更允许进一步细化或限制布局。一般我都是使用的 Layout 这样更能适应屏幕大小,具体来说,布局类型允许你:
- 设置文本和其他项目的对齐方式
- 自动调整并填充分配的应用程序区域
- 设置尺寸约束,例如最小或最大尺寸
- 设置布局中元素之间的间距
GroupBox {
id: gridBox
title: "Grid layout"
Layout.fillWidth: true
GridLayout {
id: gridLayout
rows: 3
flow: GridLayout.TopToBottom
anchors.fill: parent
Label {
text: "Line 1" }
Label {
text: "Line 2" }
Label {
text: "Line 3" }
TextField {
}
TextField {
}
TextField {
}
TextArea {
text: "This widget spans over three rows in the GridLayout.\n"
+ "All items in the GridLayout are implicitly positioned from top to bottom."
Layout.rowSpan: 3
Layout.fillHeight: true
Layout.fillWidth: true
}
}
}
上面的代码片段来自基本布局的例子。这段代码展示了在布局中添加各种字段和项目的简单性。GridLayout可以调整大小,其格式可以通过各种属性进行自定义。