4. 使用状态和状态组切换界面
任务目标
在 Qt Quick 中定义多个界面状态(State),通过按钮点击在状态间切换,使界面元素的属性(颜色、位置、尺寸、可见性等)随状态发生变化。
实现方案
使用 Item 的 states 属性定义三个状态:red、green、blue。每个状态改变矩形的颜色和按钮文字。通过 state 属性绑定当前状态,按钮点击时切换状态值。
完整代码
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
visible: true
width: 400
height: 300
title: "状态切换示例"
Rectangle {
id: colorBox
anchors.centerIn: parent
width: 200
height: 150
radius: 10
color: "gray"
// 定义三个状态
states: [
State {
name: "red"
PropertyChanges { target: colorBox; color: "#e74c3c" }
PropertyChanges { target: statusText; text: "当前状态:红色" }
},
State {
name: "green"
PropertyChanges { target: colorBox; color: "#2ecc71" }
PropertyChanges { target: statusText; text: "当前状态:绿色" }
},
State {
name: "blue"
PropertyChanges { target: colorBox; color: "#3498db" }
PropertyChanges { target: statusText; text: "当前状态:蓝色" }
}
]
// 初始状态
state: "red"
Text {
id: statusText
anchors.centerIn: parent
font.pixelSize: 18
color: "white"
text: "当前状态:红色"
}
}
Row {
anchors.bottom: parent.bottom
anchors.bottomMargin: 20
anchors.horizontalCenter: parent.horizontalCenter
spacing: 10
Button {
text: "红色"
onClicked: colorBox.state = "red"
}
Button {
text: "绿色"
onClicked: colorBox.state = "green"
}
Button {
text: "蓝色"
onClicked: colorBox.state = "blue"
}
}
}
运行方式
- 在 Qt Creator 中创建 Qt Quick Application 项目(Qt 5.15+ 或 Qt 6.x)。
- 将上述代码替换
main.qml的全部内容。 - 直接运行项目(快捷键
Ctrl+R)。
验证方法
- 启动后,矩形显示为红色,文字显示“当前状态:红色”。
- 点击“绿色”按钮,矩形变为绿色,文字同步更新。
- 点击“蓝色”按钮,矩形变为蓝色,文字同步更新。
- 点击“红色”按钮可返回初始状态。
若三个按钮均能正确切换颜色与文字,则状态定义与切换逻辑实现正确。
关键说明
states中每个State的name是唯一标识,PropertyChanges指定该状态下目标对象的属性值。- 通过给
state属性赋字符串值即可触发状态切换,无需手动恢复属性——Qt Quick 自动处理状态间的属性过渡。 - 如需动画过渡效果,可添加
transitions属性,但本案例聚焦状态切换本身,故未包含。