QML 开发实战技巧

QML 的声明式语法上手快,但属性绑定、布局、组件复用这些"看起来简单"的地方,藏着大量陷阱。本文整理 QML 日常开发中最常遇到的问题与解决方案。

1. 在 main.qml 中显示另一个 QML

关键点:QML 自定义类型要求文件名首字母大写,samegame.qml 不能直接当类型用。

方案一:改名为 SameGame.qml,直接实例化

import QtQuick
import QtQuick.Window

Window {
    width: 640
    height: 480
    visible: true

    SameGame {
        anchors.fill: parent
    }
}

方案二:Loader 加载(文件名可保持小写)

Loader {
    anchors.fill: parent
    source: "samegame.qml"
}

方案三:StackView 多页面

StackView {
    anchors.fill: parent
    initialItem: "samegame.qml"
}

特例:如果目标 QML 的根是 Window,不能嵌套进另一个 Item/Window,此时 main.qml 本身几乎只是 SameGame { visible: true }。

2. 属性绑定及其陷阱

属性绑定是 QML 最核心的机制。你声明"属性等于什么",引擎自动维护,依赖变化时自动重算。

Rectangle {
    width: 200
    height: width / 2               // 绑定:永远等于 width 的一半
    color: mouseArea.pressed ? "steelblue" : "lightsteelblue"
}

2.1 底层机制:依赖追踪

  1. 求值时记录读到了哪些属性。
  2. 这些属性变化时,绑定标记为"脏"。
  3. 下一帧重新求值。

2.2 核心陷阱:命令式赋值会切断绑定

Rectangle {
    width: parent.width / 2      // 绑定建立

    Component.onCompleted: {
        width = 300              // ❌ 绑定被切断!parent.width 再变不会更新
    }
}

为什么:命令式赋值是一次性的,引擎无法判断你是临时覆盖还是永久替换,选择保守地解除绑定。

2.3 正确做法

// 需要条件开关绑定时用 Binding 元素
Binding on width {
    value: parent.width / 2
    when: condition
}

// 需要重新建立绑定时用 Qt.binding()
width = Qt.binding(function() { return parent.width / 2 })

2.4 其它常见陷阱

陷阱 表现 解决
绑定循环 Binding loop detected 检查 A→B→A 回路,打破单向依赖
绑定里做副作用 行为不可预测 绑定表达式保持纯函数,副作用放 onXxx
C++ 属性缺 NOTIFY QML 侧不更新 Q_PROPERTY 必须声明 NOTIFY 并 emit
绑定到 JS 数组内部元素 修改元素不触发 替换整个数组或改用 ListModel
访问不存在的属性 undefined 静默传播 用 == null / === undefined 防御

3. == vs === 与 modelData

3.1 == 和 ===

Qt Creator 会警告:== and != may perform type coercion use === or !==。

== 会做隐式类型转换,"1" == 1 为 true,容易掩盖 bug。除了 null 检查,其余一律用 === / !==。

场景 写法
比较枚举/字符串/数字/对象 === / !==
检查 null 或 undefined x == null(唯一推荐 == 的场景)
消除警告但保留语义 x === null || x === undefined

3.2 modelData 使用规则

modelData 是 delegate 内隐式注入的属性,代表当前项的数据。

model 类型 推荐
数字 / 字符串数组 / JS 数组 modelData
ListModel / C++ 模型 直接用角色名(name、age)

为什么具名角色更好:

  • 可读性:name 比 modelData.name 直观。
  • 工具支持:有补全和跳转。
  • 性能:直接走角色索引,比 modelData 包装快。

嵌套陷阱:内层 Repeater 的 modelData 遮蔽外层。用外层 delegate 的 id 访问:

Repeater {
    model: ["A", "B"]
    delegate: Column {
        id: outerItem
        Repeater {
            model: [1, 2]
            delegate: Text { text: outerItem.modelData + modelData }
        }
    }
}

4. Repeater 内控件的间隔

关键认知:Repeater 本身没有 spacing 属性,它只负责复制 delegate。

间隔由包裹它的定位器/布局决定:

Column {
    spacing: 10          // ← 间隔在这里
    Repeater {
        model: 3
        delegate: Rectangle { width: 100; height: 40 }
    }
}
容器 间隔属性
Row / Column spacing
Grid spacing / rowSpacing / columnSpacing
RowLayout / ColumnLayout spacing(子项也可用 Layout.margins,但与 spacing 叠加需小心)

5. ColumnLayout vs Column

不能互换。ColumnLayout 不是 Column 的简写。

维度 Column(定位器) ColumnLayout(布局)
模块 QtQuick QtQuick.Layouts
尺寸管理 被动,依赖子项自身尺寸 主动,按 Layout.* 分配
子项填充 不支持 Layout.fillWidth: true
响应式 弱 强
子项锚点 可用 不能用(用 Layout.*)

选型:简单固定排列用 Column;响应式、子项需要智能填充用 ColumnLayout。

6. Text 水平居中

核心属性:horizontalAlignment: Text.AlignHCenter。但它只控制文本在 Text 元素内部的对齐,元素本身在父级里的位置需要另外处理。

6.1 常见写法

// 单行短文本:元素整体居中
Text { anchors.centerIn: parent }

// 多行 / 占满宽度:文本在元素内居中
Text {
    width: parent.width
    horizontalAlignment: Text.AlignHCenter
    wrapMode: Text.WordWrap
}

// 布局内
Text {
    Layout.fillWidth: true
    horizontalAlignment: Text.AlignHCenter
}

6.2 常见坑

现象 原因 解决
设了 horizontalAlignment 没居中 Text 宽度 = 文本宽度,无多余空间 设 width 或 Layout.fillWidth: true
布局里用 anchors 报错 布局子项不能用锚点 改用 Layout.alignment
多行文本不居中 只加了 wrapMode 补 horizontalAlignment

7. TabBar 标签页

QML 没有 TabControl,现代 Controls 2 用 TabBar + StackLayout/SwipeView 组合。

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

ApplicationWindow {
    width: 400; height: 300
    visible: true

    ColumnLayout {
        anchors.fill: parent

        TabBar {
            id: tabBar
            Layout.fillWidth: true
            TabButton { text: "首页" }
            TabButton { text: "发现" }
            TabButton { text: "我的" }
        }

        StackLayout {
            Layout.fillWidth: true
            Layout.fillHeight: true
            currentIndex: tabBar.currentIndex   // 双向绑定

            Rectangle { color: "lightcoral" }
            Rectangle { color: "lightgreen" }
            Rectangle { color: "lightblue" }
        }
    }
}

7.1 动态标签页

用 ListModel + Repeater 驱动:

ListModel { id: tabModel; ListElement { title: "标签 1" } }

TabBar {
    Repeater {
        model: tabModel
        TabButton { text: model.title }
    }
}

7.2 常见问题

问题 解决
找不到 TabBar 检查 import QtQuick.Controls;Qt5 需 5.7+;确保 QT += quickcontrols2
标签过多 超出宽度时 TabBar 自动变为可滚动
标签位置 TabBar { position: TabBar.Footer } 放到底部

8. 小结

主题 核心要点
显示其他 QML 类型名必须首字母大写;不改名用 Loader
绑定 声明式自动维护,命令式赋值会切断
=== 除 null 检查外一律用严格相等
modelData 简单数组用,结构化模型用角色名
Repeater 间隔 在父容器的 spacing 上设,Repeater 没有这个属性
Layout ColumnLayout 不是 Column 的简写;布局子项不能用 anchors
Text 居中 设 width + horizontalAlignment,或 anchors.centerIn
TabBar TabBar + StackLayout/SwipeView 组合,动态用 ListModel + Repeater

❤️ 如果这篇文章对你有帮助,欢迎赞助支持我继续维护 ❤️

☕ Support me ⚡ 爱发电赞助