一、?錨點布局(Anchors)
-
通過定義元素與其他元素或父容器的錨點關系實現定位,支持動態調整和邊距控制?。
Rectangle {anchors.left: parent.left // 左對齊父容器anchors.top: parent.top // 頂部對齊父容器anchors.margins: 10 // 統一設置四周邊距width: 100; height: 50 }
- ?關鍵屬性?:
anchors.left
、anchors.right
、anchors.fill
(填充父容器)、anchors.centerIn
(居中)?。 - ?邊距控制?:
anchors.margins
(統一邊距)或單獨設置anchors.leftMargin
等?。
- ?關鍵屬性?:
二、水平布局(Row)
Row定位器將子元素水平排列。你可以通過spacing
屬性來設置子元素之間的間距。主要屬性:
基本屬性
屬性 | 類型 | 默認值 | 描述 |
---|---|---|---|
spacing | real | 0 | 子元素之間的間距(像素) |
layoutDirection | enumeration | Qt.LeftToRight | 布局方向(LeftToRight/RightToLeft) |
add | Transition | - | 添加子項時應用的過渡動畫 |
move | Transition | - | 移動子項時應用的過渡動畫 |
populate | Transition | - | 初始創建子項時應用的過渡動畫 |
對齊屬性
屬性 | 類型 | 默認值 | 描述 |
---|---|---|---|
topPadding | real | 0 | 頂部內邊距 |
bottomPadding | real | 0 | 底部內邊距 |
leftPadding | real | 0 | 左側內邊距 |
rightPadding | real | 0 | 右側內邊距 |
padding | real | 0 | 統一設置所有內邊距 |
verticalAlignment | enumeration | Row.AlignTop | 垂直對齊方式(AlignTop/AlignVCenter/AlignBottom) |
horizontalAlignment | enumeration | Row.AlignLeft | 水平對齊方式(AlignLeft/AlignHCenter/AlignRight) |
布局控制屬性
屬性 | 類型 | 默認值 | 描述 |
---|---|---|---|
width | real | 隱含寬度 | 行寬度(若未設置則為子項總寬度) |
height | real | 隱含高度 | 行高度(若未設置則為最高子項高度) |
clip | bool | false | 是否裁剪超出邊界的內容 |
枚舉值說明
layoutDirection:
-
Qt.LeftToRight
- 從左到右排列(默認) -
Qt.RightToLeft
- 從右到左排列
verticalAlignment:
-
Row.AlignTop
- 頂部對齊 -
Row.AlignVCenter
- 垂直居中 -
Row.AlignBottom
- 底部對齊
horizontalAlignment:
-
Row.AlignLeft
- 左對齊 -
Row.AlignHCenter
- 水平居中 -
Row.AlignRight
- 右對齊
示例代碼:
Row {spacing: 10Rectangle { width: 100; height: 50; color: "red" }Rectangle { width: 100; height: 50; color: "green" }Rectangle { width: 100; height: 50; color: "blue" }}
Row 是創建水平排列布局的基礎組件,適合簡單的水平排列需求,對于更復雜的響應式布局,建議使用 RowLayout
或 GridLayout
。
三、RowLayout
RowLayout
是 Qt Quick Layouts 模塊提供的布局組件,用于創建靈活的水平布局。相比基礎的 Row
,它提供了更強大的布局控制能力。
基本用法
qml
import QtQuick 2.15
import QtQuick.Layouts 1.15RowLayout {id: layoutanchors.fill: parentspacing: 10 // 子項之間的間距Rectangle {color: "red"Layout.preferredWidth: 100Layout.fillHeight: true}Rectangle {color: "green"Layout.fillWidth: true // 填充可用寬度Layout.minimumWidth: 50Layout.maximumWidth: 200}Rectangle {color: "blue"Layout.preferredWidth: 150Layout.preferredHeight: 80}
}
主要特性
RowLayout 容器屬性
屬性 | 類型 | 默認值 | 說明 |
---|---|---|---|
spacing | real | 5 | 子項之間的統一間距(像素) |
layoutDirection | enum | Qt.LeftToRight | 排列方向(Qt.LeftToRight 或 Qt.RightToLeft ) |
enabled | bool | true | 是否啟用布局(禁用時子項不可見/不響應) |
子項布局屬性(需在子元素內使用)
1. 尺寸控制
屬性 | 類型 | 說明 |
---|---|---|
Layout.fillWidth | bool | 是否水平填充剩余空間 |
Layout.fillHeight | bool | 是否垂直填充剩余空間 |
Layout.preferredWidth | real | 首選寬度(優先級高于隱式寬度) |
Layout.preferredHeight | real | 首選高度 |
Layout.minimumWidth | real | 最小寬度限制 |
Layout.minimumHeight | real | 最小高度限制 |
Layout.maximumWidth | real | 最大 |