定位器和布局
在 QML 中,有多种方法可以定位控件。
以下是简要概述。更多详细信息,请参阅《Qt Quick 中的重要概念——定位》。
手动定位
通过设置项的 x、y 属性,可将其放置在屏幕上的特定 x、y 坐标处。这将根据视觉坐标系的规则,将其位置相对于父元素的左上角进行定位。
若将这些属性设置为绑定而非常量值,只需将 x 和 y 坐标设置为相应的绑定,即可轻松实现相对定位。
import QtQuick
Item {
width: 100; height: 100
Rectangle {
// Manually positioned at 20,20
x: 20
y: 20
width: 80
height: 80
color: "red"
}
}
锚点
Item 类型提供了锚定到其他Item 类型的功能。 每个项目有七条锚点线:左侧、右侧、垂直中心、顶部、底部、基线和水平中心。三条垂直锚点线可以锚定到另一个项目的任意三条垂直锚点线,四条水平锚点线可以锚定到另一个项目的水平锚点线。
有关完整细节,请参阅《使用锚点定位》以及anchors property 的文档。
import QtQuick
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"
}
}
定位器
对于希望以规则模式定位一组元素的常见情况,Qt Quick 提供了一些定位器类型。放置在定位器中的元素会自动以某种方式定位;例如,Row 会将元素定位为水平相邻(形成一行)。
完整详情请参阅“项目定位器”。
import QtQuick
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" }
}
}
布局类型
布局类型的工作方式与定位器类似,但允许对布局进行进一步的精细调整或限制。具体而言,布局类型允许您:
- 设置文本和其他项的对齐方式
- 自动调整大小并填充分配的应用程序区域
- 设置尺寸限制,例如最小或最大尺寸
- 设置布局中各元素之间的间距
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 可以调整大小,其格式可通过各种属性进行自定义。
有关布局类型的更多信息,请访问:
注意: Qt Quick Layouts 该功能于 Qt 5.1 中引入,需要 Qt Quick 2.1。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.