第 6 课:Qt Quick Controls 标准控件
更新: 10/23/2026 字数: 0 字 时长: 0 分钟
前面我们用的 Rectangle、Text、MouseArea 都是 Qt Quick 的基础元素。
如果要写正常应用界面,比如按钮、输入框、滑块、下拉框,应该用 Qt Quick Controls。
Qt Quick Controls 是官方提供的一套标准 UI 控件。
使用 Qt Quick Controls 构建标准界面
第一步:导入 Controls
在 QML 文件顶部加:
import QtQuick
import QtQuick.ControlsQt 6 里通常不写版本号,直接 import QtQuick.Controls 即可。
第二步:用 ApplicationWindow
以前我们用 Window。
用 Controls 时,推荐用 ApplicationWindow,它是专门为应用设计的窗口,支持菜单栏、工具栏、页脚等。
把 Main.qml 改成:
import QtQuick
import QtQuick.Controls
ApplicationWindow {
width: 420
height: 360
visible: true
title: "第六课"
Column {
anchors.centerIn: parent
spacing: 12
Button {
text: "点我"
onClicked: console.log("按钮被点击了")
}
TextField {
id: input
width: 200
placeholderText: "请输入内容"
}
Label {
text: "你输入了: " + input.text
}
Slider {
width: 200
from: 0
to: 100
value: 50
onValueChanged: console.log("当前值: " + value)
}
CheckBox {
text: "同意条款"
checked: true
}
ComboBox {
width: 200
model: ["苹果", "香蕉", "橙子"]
onActivated: console.log("选择了: " + currentText)
}
}
}运行后你会看到一组标准控件,都可以交互。
常用控件说明
1. Button
Button {
text: "点我"
onClicked: console.log("点击")
}标准按钮,自带视觉、按下状态、键盘支持。
2. Label
Label {
text: "一段文字"
}比 Text 更适合做界面文字,会自动跟随控件样式和字体设置。
3. TextField
TextField {
placeholderText: "请输入内容"
}单行输入框。placeholderText 是占位提示。
4. TextArea
多行输入框:
TextArea {
width: 200
height: 80
placeholderText: "多行输入"
}5. CheckBox
CheckBox {
text: "同意条款"
checked: true
}复选框,checked 表示是否勾选。
6. RadioButton
单选框,通常配合 ButtonGroup 使用:
ButtonGroup { id: group }
Column {
RadioButton { text: "选项 A"; checked: true; ButtonGroup.group: group }
RadioButton { text: "选项 B"; ButtonGroup.group: group }
}7. Switch
开关:
Switch {
text: "启用"
checked: true
}8. Slider
滑块:
Slider {
from: 0
to: 100
value: 50
}9. ProgressBar
进度条:
ProgressBar {
value: 0.6
}10. ComboBox
下拉框:
ComboBox {
model: ["苹果", "香蕉", "橙子"]
onActivated: console.log(currentText)
}11. SpinBox
数字微调框:
SpinBox {
from: 1
to: 100
value: 10
}12. Dialog
对话框:
Dialog {
id: dialog
title: "提示"
standardButtons: Dialog.Ok
Text { text: "这是一个对话框" }
}
Button {
text: "打开对话框"
onClicked: dialog.open()
}关于样式
Qt Quick Controls 支持多种样式:
- Basic
- Fusion
- Material
- Universal
- macOS
- Windows
可以在 C++ 里设置:
QQuickStyle::setStyle("Fusion");也可以设置环境变量:
QT_QUICK_CONTROLS_STYLE=Material初学阶段先不用管样式,默认样式就够用。
你的动手练习
练习 1
做一个“打招呼”小表单:
- 一个
TextField输入名字 - 一个
Button,文字“打招呼” - 一个
Label显示结果
点击按钮后,Label 显示:
你好,xxx练习 2
用 Slider 控制一个 Rectangle 的宽度:
Rectangle {
id: bar
height: 30
color: "steelblue"
width: slider.value
}练习 3
用 CheckBox 控制一个 Rectangle 是否可见:
Rectangle {
visible: check.checked
}练习 4
用 ComboBox 选择颜色,改变一个矩形的颜色:
ComboBox {
id: colorBox
model: ["红色", "绿色", "蓝色"]
}根据 currentIndex 设置颜色。
练习 5(思考题)
Button 的 onClicked 和 MouseArea 的 onClicked 有什么区别?
为什么有 Button 之后,大多数按钮场景不再直接用 MouseArea?