QC++ / Qt 学习之路

Qt Quick Controls 与现代界面

用官方控件库与模型视图搭建完整现代界面

进阶第 36 / 48 章第五篇 · QML 与实战项目

#Qt Quick Controls 是什么

上一篇的 Rectangle、Text、MouseArea 是 QtQuick 模块提供的基元(primitives),它们只负责"画"和"响应",不带任何外观规范。要做出一个像样的应用,你还需要按钮、输入框、下拉框、列表、标签页这些东西——这就是 Qt Quick Controls(模块名 QtQuick.Controls)的职责。它相当于 Widgets 里的 QPushButton/QLineEdit/QListView 那一层。

一个典型的 Controls 应用骨架是这样的层级:

QML
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

ApplicationWindow {          // 顶层窗口,自带 menuBar/header/footer/overlay
    visible: true
    width: 900; height: 600
    title: "我的应用"

    header: ToolBar {        // 顶部工具栏
        RowLayout {
            anchors.fill: parent
            ToolButton { text: "菜单"; onClicked: drawer.open() }
            Label { text: "首页"; Layout.fillWidth: true }
        }
    }

    Drawer {                 // 侧边抽屉菜单
        id: drawer
        width: 240
        edge: Qt.LeftEdge
        Column {
            anchors.fill: parent
            ItemDelegate { text: "仪表盘"; width: parent.width }
            ItemDelegate { text: "设置";   width: parent.width }
        }
    }

    Page {                   // 内容页,自带 header/footer 区域
        anchors.fill: parent
        Button { anchors.centerIn: parent; text: "确定" }
    }
}

ApplicationWindow 是最重要的顶层容器,它比裸 Window 多了 header、footer、menuBar、overlay(弹层容器,Popup 会自动挂到它下面,因此不必担心 z 序)。页面切换通常在 Page + StackView 之间做,而不是手动 new 一堆窗口。

#常用控件一览

控件对应 Widgets关键属性/信号
Button / ToolButton / RoundButtonQPushButtontext、onClicked、checkable、icon.source
TextFieldQLineEditplaceholderText、onAccepted(回车)、validator、echoMode
TextAreaQTextEditwrapMode、textFormat
ComboBoxQComboBoxmodel、currentIndex、currentText、editable
CheckBox / Switch / RadioButtonQCheckBox 等checked、onToggled
Slider / ProgressBar / BusyIndicator同名from/to/value、indeterminate
ListViewQListViewmodel、delegate、currentIndex
SwipeView + TabBarQTabWidget需手动联动 currentIndex
Drawer / Popup / DialogQDockWidget / QDialogopen()/close()、modal、dim

Popup 家族是 QML 的强项:Popup 是基类,Dialog(带标题栏与标准按钮)、Menu(右键/下拉菜单)、ToolTip、Drawer(从边缘滑出)都是它的子类。它们渲染在 overlay 上,天然不会被父元素裁剪——这在 Widgets 里要靠 QDialog 独立窗口才能实现。

QML
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Page {
    // 表单 + 校验 + 弹窗
    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 24
        spacing: 12

        TextField {
            id: nameField
            Layout.fillWidth: true
            placeholderText: "请输入名称(至少 3 个字符)"
            onTextChanged: nameOk = (text.length >= 3)
        }

        RowLayout {
            ComboBox {
                id: typeBox
                Layout.fillWidth: true
                model: ["标准", "高级", "自定义"]
            }
            Switch { id: enableSwitch; checked: true; text: "启用" }
        }

        Button {
            text: "提交"
            enabled: nameOk && enableSwitch.checked   // 绑定驱动可用状态
            Layout.alignment: Qt.AlignHCenter
            onClicked: confirmDlg.open()
        }
    }

    property bool nameOk: false

    Dialog {
        id: confirmDlg
        anchors.centerIn: parent
        modal: true
        title: "确认"
        standardButtons: Dialog.Ok | Dialog.Cancel
        Label { text: "提交 " + nameField.text + "(" + typeBox.currentText + ")?" }
        onAccepted: console.log("已提交")
    }
}

注意 enabled: nameOk && enableSwitch.checked——不需要写任何同步代码,可用状态由输入自动推导。这是声明式带来的直接收益。

#样式系统

Qt 6 的 Controls 采用"可替换的默认样式"架构,同一份 QML 代码在不同平台会呈现不同观感。可用样式有:

  • Basic:最朴素,纯 QML 实现,是其他样式的基类;
  • Fusion:跨平台一致的"融合"外观,类似 Qt Widgets 的 Fusion 风格;
  • Material:Google Material Design(Qt 5.12 起官方提供);
  • Universal:微软 Fluent/Universal;
  • macOS / Windows:Qt 6.5+ 提供的原生风格(部分为商业版特性)。

切换样式有三种方式,优先级从低到高。最低的是环境变量:在启动程序前设置 QT_QUICK_CONTROLS_STYLE=Material,不改一行代码就能看到不同观感,最适合做样式的 A/B 对比。其次是 C++ 代码里调用 QQuickStyle::setStyle(),注意它必须在 QGuiApplication 构造之前执行,否则已经创建的控件不会被重新加载。最高优先级、也最推荐用于发布的是第三种——随资源打包配置文件:

C++
// 方式二:C++ 中在构造 QGuiApplication 之前设置
#include <QGuiApplication>
#include <QQuickStyle>

int main(int argc, char *argv[])
{
    QQuickStyle::setStyle("Material");      // 必须在 QGuiApplication 之前
    QGuiApplication app(argc, argv);
    // ...
}
QML
// 方式三:qtquickcontrols2.conf 配置文件(随资源打包,推荐用于发布)
[Controls]
Style=Material

[Material]
Theme=Dark
Accent=Teal
Primary=BlueGrey

把 qtquickcontrols2.conf 放进 qrc 资源的根路径(:/qtquickcontrols2.conf),发布包里的观感就固定了,不依赖用户环境变量。单个控件还能用 Material.theme、Material.accent 这类附加属性做局部覆盖,例如 Button { Material.background: "#FF5722" },只影响这一个按钮。

样式系统最大的价值在于同一份 QML 代码可以在不同平台呈现不同观感,而不需要你写 if (Windows) ... else if (macOS) ... 这类分支。这也意味着你在设计界面时不要硬编码具体像素值或颜色,而应使用控件自带的尺寸提示(implicitWidth/implicitHeight),让样式决定最终数值,否则换成 Material 样式后布局会走形。实践中建议先选定一种样式作为基准(通常选 Fusion 或 Basic,二者的尺寸最"中性"),再针对其他样式做个别微调。

深层定制(改圆角、改内边距)要用控件模板:Controls 的每个控件都由对外接口(Button.qml)与内部结构(contentItem 与 background)组成,定制时只重写这两项即可,不必重写整个控件,也不会丢失点击、键盘、可用性这些行为逻辑。这是 Controls 相比"自己用 Rectangle 拼一个按钮"最大的优势——外观随便换,交互语义仍是官方实现,无障碍与键盘导航都还在。下面的例子只换了外观,按下、悬停、可用状态全部照旧:

QML
    background: Rectangle {
        implicitWidth: 120; implicitHeight: 40
        radius: height / 2
        color: parent.down ? "#303F9F" : (parent.hovered ? "#7986CB" : "#3F51B5")
        Behavior on color { ColorAnimation { duration: 120 } }
    }
    contentItem: Text {
        text: parent.text
        color: "white"
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
    }
}

#模型与视图:ListModel + ListView

QML 的视图(ListView / GridView / TableView / Repeater)都遵循同一套 model-delegate 模式:模型提供数据,委托(delegate)定义"一条数据长什么样"。视图只负责创建、回收可见范围内的委托实例——不会为 10000 条数据创建 10000 个对象,这是它能流畅处理大列表的原因。

QML
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Page {
    ListModel {                        // 静态模型,也可换成 JS 数组 / C++ 模型
        id: taskModel
        ListElement { name: "采集服务"; status: "运行中"; cpu: 12 }
        ListElement { name: "告警引擎"; status: "已停止"; cpu: 0 }
        ListElement { name: "数据库";   status: "运行中"; cpu: 45 }
    }

    ListView {
        id: view
        anchors.fill: parent
        model: taskModel
        spacing: 4
        clip: true

        delegate: ItemDelegate {        // 每条数据的呈现方式
            width: view.width
            height: 64

            contentItem: RowLayout {
                ColumnLayout {
                    Layout.fillWidth: true
                    Label { text: model.name; font.bold: true }
                    Label {
                        text: "CPU " + model.cpu + "%"
                        color: "#757575"; font.pixelSize: 12
                    }
                }
                Rectangle {             // 状态指示灯,颜色由数据决定
                    width: 12; height: 12; radius: 6
                    color: model.status === "运行中" ? "#4CAF50" : "#F44336"
                }
            }

            // 委托内的按钮,直接操作模型
            onClicked: taskModel.setProperty(index, "cpu", model.cpu + 1)
        }

        // 高亮条
        highlight: Rectangle { color: "#E3F2FD"; radius: 4 }

        // 空列表提示
        Text {
            anchors.centerIn: parent
            visible: view.count === 0
            text: "暂无任务"
            color: "#9E9E9E"
        }
    }

    footer: Button {
        text: "新增"
        width: parent.width
        onClicked: taskModel.append({ name: "新任务", status: "运行中", cpu: 0 })
    }
}

要点:

  • 委托内部可以直接用 model.xxx(或省略 model. 前缀)和 index 这两个隐式变量。
  • 修改数据用 ListModel 的 append/insert/remove/setProperty 方法;直接替换整个 model 会重建所有委托,滚动位置也会丢。
  • 数据源来自 C++ 时,把 model 换成 QAbstractListModel 子类(见下一章),委托代码一行都不用改——这就是 model-delegate 解耦的价值。

理解 model-delegate 最重要的一点,是委托实例会被复用。你看到的屏幕上那十几个条目,在滚动时会被回收再用于新的数据行,因此绝不能在委托里保存与某条数据相关的状态(比如"这一行是否被展开");这类状态必须存在 model 里,或者用 delegate 外部的集合记录,否则滚几下就会发现展开状态串到了别的行上。这是 QML 列表开发中最隐蔽的一类 bug,排查时往往以为是数据错了,实际是委托状态没跟着数据走。

数量少、不需要滚动的场景用 Repeater 更轻量,它必须配合定位器(Row/Column/Grid)或布局使用:

QML
RowLayout {
    spacing: 8
    Repeater {
        model: ["CPU", "内存", "磁盘", "网络"]
        delegate: Rectangle {
            required property string modelData
            Layout.fillWidth: true; height: 40; radius: 4
            color: "#ECEFF1"
            Label { anchors.centerIn: parent; text: modelData }
        }
    }
}

Qt 6 要求 Repeater 的委托用 required property 显式声明用到的 index/modelData,漏写会报错。这是 Qt 6 为了性能做的收紧,属于常见升级坑。

#状态、过渡与动画

QML 把"界面在不同条件下的样子"抽象成 State,把"切换过程"抽象成 Transition。

QML
import QtQuick
import QtQuick.Controls

Rectangle {
    id: card
    width: 260; height: 160
    radius: 10
    color: "#FFFFFF"
    border.color: "#E0E0E0"

    // 默认状态声明所有"可变属性"的初值
    states: [
        State {
            name: "normal"
            PropertyChanges { target: card; color: "#FFFFFF"; scale: 1.0 }
            PropertyChanges { target: shadow; opacity: 0.15 }
        },
        State {
            name: "active"
            PropertyChanges { target: card; color: "#FFF3E0"; scale: 1.05 }
            PropertyChanges { target: shadow; opacity: 0.35 }
        }
    ]
    state: "normal"

    transitions: [
        Transition {
            from: "*"; to: "*"                 // 任意状态间切换都适用
            NumberAnimation { properties: "scale"; duration: 200; easing.type: Easing.OutBack }
            ColorAnimation { properties: "color"; duration: 200 }
            NumberAnimation { properties: "opacity"; duration: 200 }
        }
    ]

    Rectangle { id: shadow; anchors.fill: parent; color: "black"; radius: 10; z: -1 }

    MouseArea {
        anchors.fill: parent
        onPressed:  card.state = "active"
        onReleased: card.state = "normal"
    }
}

如果只想让某单个属性在变化时自带动画,用 Behavior 更省事(Behavior on x { NumberAnimation { duration: 300 } })。常用动画类型:NumberAnimation、ColorAnimation、RotationAnimation、PropertyAnimation(通用,按 property: "width" 指定)、SequentialAnimation/ParallelAnimation(组合)、PauseAnimation、SpringAnimation(弹性)。

动画的性能红线:动画只改 x/y/scale/opacity/rotation 这类由场景图直接处理的属性时开销极低;一旦动画触发 width/height(进而触发子对象重新布局)或改了 Text 的 text,就会引发整棵子树重排,帧率会明显下降。列表滚动卡顿多半是这个原因。

#小结

  1. ApplicationWindow + Page + StackView 是 Controls 应用的标准骨架;Popup/Drawer/Dialog 渲染在 overlay 上自动解决层级问题。
  2. 控件的可用状态、文本内容应尽量写成绑定表达式,而不是在某处手动 enabled = true。
  3. 样式切换优先用 qtquickcontrols2.conf(随 qrc 打包),局部微调用 Material.accent 这类附加属性,深度定制重写 background/contentItem。
  4. 视图遵循 model-delegate 模式,ListModel 与 QAbstractListModel 可互换而委托不变;Qt 6 的 Repeater 委托必须用 required property 声明 modelData/index。
  5. 动画优先改 x/y/scale/opacity/rotation,避免动画 width/height 与文本,否则会引发重排掉帧。

#练习

  1. 用 SwipeView + TabBar 做一个三页切换界面,要求双向联动 currentIndex(提示:用绑定会在双向绑定时冲突,改用 onCurrentIndexChanged 单向同步其中一侧)。
  2. 做一个 To-Do 列表:TextField 回车添加,ListView 展示,左滑或点击复选框标为完成(文字加删除线并变灰),支持 remove 删除,空列表显示占位提示。
  3. 给列表项加入场动画:新添加的条目从右侧滑入并淡入(提示:ListView 的 add 过渡,或在委托的 Component.onCompleted 中触发 NumberAnimation)。
  4. 用 State + Transition 实现登录按钮的三种状态:idle / loading(显示 BusyIndicator 并禁用)/ success(变绿并打勾),点击后模拟 2 秒异步过程。
我的学习笔记笔记总览
笔记保存在本机浏览器(localStorage),换设备或清理缓存会丢失;重要内容请点「导出全部笔记」存成 .md 文件。