4. QtMCU状态机
任务目标
在Qt Quick中为一个界面元素定义多个状态(states),并使用Transition定义状态切换时的动画效果。本案例以一个可点击的矩形卡片为例,实现默认态 → 高亮态 → 选中态的切换,每次切换伴随颜色、缩放与圆角半径的平滑过渡。
环境依赖
Qt 5.15+ 或 Qt 6.x,Qt Quick模块。无需额外安装包,使用qmlscene或Qt Creator直接运行QML文件即可。
关键完整代码
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
width: 400; height: 300
visible: true
title: "State & Transition Demo"
Rectangle {
id: card
width: 160; height: 100
anchors.centerIn: parent
radius: 4
color: "#4A90D9"
// 鼠标点击切换状态
MouseArea {
anchors.fill: parent
onClicked: {
if (card.state === "normal")
card.state = "hovered"
else if (card.state === "hovered")
card.state = "selected"
else
card.state = "normal"
}
}
// 状态定义
states: [
State {
name: "normal"
PropertyChanges { target: card; color: "#4A90D9"; scale: 1.0; radius: 4 }
},
State {
name: "hovered"
PropertyChanges { target: card; color: "#7CB342"; scale: 1.1; radius: 12 }
},
State {
name: "selected"
PropertyChanges { target: card; color: "#F4511E"; scale: 0.9; radius: 20 }
}
]
// 状态切换动画
transitions: [
Transition {
from: "*"; to: "*"
ColorAnimation { duration: 300 }
NumberAnimation { properties: "scale,radius"; duration: 300; easing.type: Easing.OutQuad }
}
]
// 当前状态文字提示
Text {
anchors.centerIn: parent
text: card.state
color: "white"
font.pixelSize: 16
font.bold: true
}
}
}
运行方式
- 将上述代码保存为
StateTransition.qml。 - 在终端执行:
qmlscene StateTransition.qml,或在Qt Creator中打开并运行。
验证方法
- 启动后卡片为蓝色圆角小矩形,中央文字显示
normal。 - 连续点击卡片,状态依次切换为
hovered(绿色、放大、圆角增大)→selected(橙色、缩小、圆角更大)→normal,循环往复。 - 每次切换时,颜色、缩放和圆角均以约300ms平滑动画过渡,而非瞬间跳变,即证明Transition生效。
关键说明
PropertyChanges用于定义不同状态下目标属性的终值;Transition中的from:"*"; to:"*"表示任意状态间切换均触发动画。- 若省略
transitions,状态切换会瞬间完成;添加后所有属性变化自动按指定动画插值。 - 本案例仅演示三个状态的循环切换,实际项目中可将状态绑定到业务逻辑(如选中、悬停、禁用等)。