- 1. QML 中常用的布局控件
- 1.1. Row
- 1.2. Column
- 1.3. Grid
- 1.4. RowLayout
- 1.5. ColumnLayout
- 1.6. GridLayout
- 1.7. 總結
1. QML 中常用的布局控件
1.1. Row
背景知識:Row 布局用于將子元素水平排列,適合簡單的線性布局,如工具欄按鈕或表單輸入項。
使用方法:
Row {spacing: 10Rectangle { width: 100; height: 100; color: "red" }Rectangle { width: 100; height: 100; color: "blue" }
}
詳細介紹:子元素從左到右依次排列,可以通過 spacing
屬性設置子元素之間的間距。
1.2. Column
背景知識:Column 布局用于將子元素垂直排列,適合需要從上到下閱讀的場景。
使用方法:
Column {spacing: 10Rectangle { width: 100; height: 100; color: "green" }Rectangle { width: 100; height: 100; color: "yellow" }
}
詳細介紹:子元素從上到下依次排列,可以通過 spacing
屬性設置子元素之間的間距。
1.3. Grid
背景知識:Grid 布局用于將子元素按照網格形式排列,適合需要等距對齊的場景,如儀表盤或圖片縮略圖列表。
使用方法:
Grid {columns: 2spacing: 10Rectangle { width: 100; height: 100; color: "red" }Rectangle { width: 100; height: 100; color: "blue" }Rectangle { width: 100; height: 100; color: "green" }Rectangle { width: 100; height: 100; color: "yellow" }
}
詳細介紹:通過 columns
屬性定義網格的列數,子元素自動填充網格單元。
1.4. RowLayout
背景知識:RowLayout 是 Row 的增強版,提供更多的布局功能,如自動調整子元素大小以填充可用空間。
使用方法:
RowLayout {anchors.fill: parentRectangle {Layout.fillWidth: truecolor: "red"height: 50}Rectangle {Layout.preferredWidth: 50color: "blue"height: 50}
}
詳細介紹:可以通過 Layout.fillWidth
和 Layout.preferredWidth
屬性控制子元素的寬度。
1.5. ColumnLayout
背景知識:ColumnLayout 是 Column 的增強版,提供更多的布局功能。
使用方法:
ColumnLayout {anchors.fill: parentRectangle {Layout.fillHeight: truecolor: "green"width: 50}Rectangle {Layout.preferredHeight: 50color: "yellow"width: 50}
}
詳細介紹:可以通過 Layout.fillHeight
和 Layout.preferredHeight
屬性控制子元素的高度。
1.6. GridLayout
背景知識:GridLayout 是一種更靈活的網格布局,允許定義行和列,并支持復雜的布局需求。
使用方法:
GridLayout {columns: 2rows: 2spacing: 10Rectangle { width: 100; height: 100; color: "red" }Rectangle { width: 100; height: 100; color: "blue" }Rectangle { width: 100; height: 100; color: "green" }Rectangle { width: 100; height: 100; color: "yellow" }
}
詳細介紹:通過 columns
和 rows
屬性定義網格的行列數,子元素自動填充網格單元。
1.7. 總結
以上是 QML 中常用的布局控件,每種控件都有其特定的使用場景和優勢。通過合理組合這些控件,可以創建復雜且美觀的用戶界面。