跳转到内容

第 4 课:布局管理 ​

更新: 10/23/2026 字数: 0 字 时长: 0 分钟

这一课学四种东西:

  1. Row:水平排列
  2. Column:垂直排列
  3. Grid:网格排列
  4. anchors:锚点定位

它们都能“摆放元素”,但用途不同。

使用 Row、Column、Grid 与 anchors 进行布局管理 ​

1. Column:垂直排列 ​

qml
import QtQuick
import QtQuick.Window

Window {
    width: 320
    height: 320
    visible: true

    Column {
        anchors.centerIn: parent
        spacing: 10

        Rectangle { width: 200; height: 40; color: "tomato" }
        Rectangle { width: 200; height: 40; color: "orange" }
        Rectangle { width: 200; height: 40; color: "gold" }
    }
}

说明:

  • Column 会把子元素从上到下排列。
  • spacing: 10 是元素之间的间隔。
  • Column 本身没有背景,只是布局容器。

2. Row:水平排列 ​

把 Column 改成 Row:

qml
Row {
    anchors.centerIn: parent
    spacing: 10

    Rectangle { width: 60; height: 60; color: "tomato" }
    Rectangle { width: 60; height: 60; color: "orange" }
    Rectangle { width: 60; height: 60; color: "gold" }
}

子元素会从左到右排列。


3. Grid:网格排列 ​

qml
Grid {
    anchors.centerIn: parent
    columns: 2
    spacing: 10

    Rectangle { width: 80; height: 80; color: "tomato" }
    Rectangle { width: 80; height: 80; color: "orange" }
    Rectangle { width: 80; height: 80; color: "gold" }
    Rectangle { width: 80; height: 80; color: "skyblue" }
}

说明:

  • columns: 2 表示每行放 2 个。
  • 自动换行。
  • 也可以写 rows: 2,效果类似。

4. anchors:锚点定位 ​

anchors 更适合做“相对父元素或兄弟元素定位”的布局。常用写法:

qml
Rectangle {
    id: header
    width: parent.width
    height: 60
    color: "steelblue"
}

Rectangle {
    id: footer
    width: parent.width
    height: 60
    color: "gray"
    anchors.bottom: parent.bottom
}

Rectangle {
    anchors.top: header.bottom
    anchors.bottom: footer.top
    anchors.left: parent.left
    anchors.right: parent.right
    color: "lightyellow"
}

这段代码实现了一个经典三栏布局:

  • 顶部栏固定在顶部
  • 底部栏固定在底部
  • 中间自动填充剩余空间

布局方式怎么选 ​

  • 一排或一列简单排列 → Row / Column
  • 网格状 → Grid
  • 需要相对父元素或兄弟元素精确对齐 → anchors
  • 需要响应式、自动分配空间 → QtQuick.Layouts(下一课再讲)

你的动手练习 ​

练习 1 ​

用 Column 做一个“登录表单”的样子:

qml
Column {
    anchors.centerIn: parent
    spacing: 12

    Rectangle { width: 240; height: 40; color: "white"; border.color: "gray" }
    Rectangle { width: 240; height: 40; color: "white"; border.color: "gray" }
    Rectangle { width: 240; height: 44; color: "steelblue"; radius: 6 }
}

第一个和第二个当输入框,第三个当登录按钮。

练习 2 ​

用 Grid 做一个 3x3 的颜色格子:

qml
Grid {
    anchors.centerIn: parent
    columns: 3
    spacing: 4

    Repeater {
        model: 9
        Rectangle {
            width: 60
            height: 60
            color: Qt.hsla(index / 9, 0.6, 0.6, 1)
        }
    }
}

Repeater 会根据 model 数量重复生成子元素,index 是当前序号。先跑起来看看效果,下一课会细讲。

练习 3 ​

用 anchors 做一个顶部标题栏 + 中间内容区 + 底部状态栏:

  • 顶部高 50,颜色 steelblue
  • 底部高 30,颜色 gray
  • 中间自动填满

练习 4(思考题) ​

如果一个元素既写了:

qml
anchors.centerIn: parent
x: 100

它最终会在哪里?为什么?