本章我们将继续探索QT Quick中常用的交互式可视化组件。这些组件是构建现代、友好用户界面的基石,提供了从简单选择到复杂导航的多种交互方式。我们将结合代码示例、属性说明和架构关系进行详细讲解。
model(数据模型)、currentIndex(选中索引)、currentText(选中文本),常用信号有activated(选中触发)、currentIndexChanged(索引变更)。value(当前值)、from/to(取值范围)、stepSize(步长),常用信号为valueModified(数值修改触发)。moved(旋钮移动触发)。MenuItem(菜单项)、MenuSeparator(分隔线),常用方法popup()(弹出)、open()(打开)。ComboBox是经典下拉选择控件,数据模型支持简单字符串列表或复杂ListModel,还可自定义下拉项样式:
import QtQuick.Controls 2.15
ComboBox {
id: combo
width: 200
model: ["选项一", "选项二", "选项三", "选项四"]
currentIndex: 1 // 默认选中第二项
onActivated: {
console.log("选中了:", currentText, "索引:", currentIndex)
}
// 自定义下拉项样式
delegate: ItemDelegate {
width: combo.width
text: modelData
highlighted: combo.highlightedIndex === index
background: Rectangle {
color: highlighted ? "#81C784" : "white"
}
}
}
它的核心属性说明:
model:支持数组或ListModel,默认null;currentIndex:当前选中索引,默认-1(未选中);currentText:选中项显示文本,默认空字符串;editable:是否允许编辑输入,默认false;displayText:主按钮显示的格式化文本,默认与currentText一致。两者均用于调节数值,但交互方式不同:SpinBox侧重精确输入,Dial侧重直观操作。可通过value属性双向绑定实现数值同步:
Row {
spacing: 40
SpinBox {
id: spinbox
from: 0
to: 100
value: 50
stepSize: 5
onValueModified: dial.value = value
}
Dial {
id: dial
from: 0
to: 100
value: 50
stepSize: 5
onMoved: spinbox.value = value
background: Rectangle {
color: "transparent"
border.color: "#4CAF50"
border.width: 3
radius: width/2
}
}
}
这些组件常结合构建标签页导航和设置界面,实现状态联动与交互提示:
import QtQuick.Controls 2.15
Column {
spacing: 20
// 开关控件
Switch {
id: sw
text: "启用高级功能"
ToolTip.visible: hovered
ToolTip.text: "开启后下方标签页将解锁更多选项"
}
// 标签栏
TabBar {
id: bar
width: parent.width
TabButton { text: "基本设置"; enabled: !sw.checked }
TabButton { text: "高级设置"; enabled: sw.checked }
TabButton { text: "关于" }
}
// 与TabBar对应的内容堆栈
StackLayout {
width: parent.width
currentIndex: bar.currentIndex
Rectangle { color: "#E8F5E9"; Label { text: "这里是基本设置..." } }
Rectangle { color: "#FFF3E0"; Label { text: "高级功能已解锁!" } }
Rectangle { color: "#E3F2FD"; Label { text: "软件信息..." } }
}
}
在QT Quick Controls 2体系中,组件层级与关联如下:
value双向绑定同步数值,Menu由按钮触发,TabBar与StackLayout联动切换内容。💡 设计提示:
Accessible.name和Accessible.description,适配屏幕阅读器;将Menu与Action结合,可实现命令集中管理与复用,同一Action可同时用于工具栏、上下文菜单:
ApplicationWindow {
id: window
width: 400; height: 300
// 定义Action
Action {
id: copyAction
text: "复制"
shortcut: "Ctrl+C"
icon.name: "edit-copy"
onTriggered: console.log("执行复制")
}
Action {
id: pasteAction
text: "粘贴"
shortcut: "Ctrl+V"
enabled: false // 可动态禁用
onTriggered: console.log("执行粘贴")
}
// 工具栏按钮使用Action
header: ToolBar {
ToolButton { action: copyAction }
ToolButton { action: pasteAction }
}
// 上下文菜单也使用相同的Action
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.RightButton
onClicked: contextMenu.popup()
Menu {
id: contextMenu
MenuItem { action: copyAction }
MenuItem { action: pasteAction }
MenuSeparator {}
MenuItem { text: "自定义操作" }
}
}
}