QML 属性动画、行为动画与预定义动画
目录
- 引言
- 相关阅读
- 本文使用的动画属性
- 工程结构
- 示例解析
- 示例1:属性动画应用
- 示例2:行为动画实现
- 示例3:预定义动画
- 总结
- 工程下载
引言
QML动画系统为界面元素提供了流畅的过渡效果。本文通过三个示例,结合属性动画(PropertyAnimation)、行为动画(Behavior),展示如何使用QML动画实现动态效果。
相关阅读
- PropertyAnimation官方文档
- NumberAnimation官方文档
- Behavior官方文档
本文使用的动画属性
属性 | 适用对象 | 说明 |
---|---|---|
target | Animation | 指定动画目标对象 |
properties | PropertyAnimation | 指定要动画化的属性列表 |
duration | Animation | 动画持续时间(毫秒) |
easing.type | Animation | 动画缓动曲线类型 |
running | Animation | 控制动画运行状态 |
onStopped | Animation | 动画停止时触发的信号 |
工程结构
qml_animation/
├── PropertyAnimationDemo.qml # 属性动画示例
├── BehaviorAnimation.qml # 行为动画示例
├── PredefinedAnimation.qml # 预定义动画示例
├── images/
│ ├── huaji.gif # 滑稽表情动画资源
│ └── rotation.gif # 旋转箭头资源
└── main.qml # 主入口文件
示例解析
示例1:属性动画应用
PropertyAnimationDemo.qml
import QtQuick
import QtQuick.ControlsRectangle {id: rootwidth: 400height: 400AnimatedImage {id: imgsource: "qrc:/images/huaji.gif"x: 0y: 150width: 100height: 100// 属性动画PropertyAnimation on x {id: propAnimto: 300duration: 500running: falseonStopped: {to = to===300 ? 0 : 300}}}Button {text: "启动属性动画"anchors.bottom: parent.bottomonClicked: {if (propAnim.running) return;propAnim.start();}}
}
代码说明:
- 通过
PropertyAnimation on x
声明x坐标属性动画 - 设置动画终点值
to
和持续时间duration
- 按钮点击触发动画启动,防止重复触发
- 动画停止时切换终点值实现往复运动
运行效果:
- 初始位置:图片位于左侧
- 点击按钮后:图片在500ms内平滑移动到右侧
- 再次点击:图片返回左侧位置,重新开始从左至右的运动
示例2:行为动画实现
BehaviorAnimation.qml
import QtQuick
import QtQuick.ControlsRectangle {width: 400height: 400AnimatedImage {id: behaviorImgsource: "qrc:/images/huaji.gif"x: 150y: 150width: 100height: 100// 默认行为动画Behavior on x {NumberAnimation {duration: 500easing.type: Easing.OutBounce}}}Row {anchors.bottom: parent.bottomspacing: 10Button {text: "左移50"onClicked: behaviorImg.x -= 50}Button {text: "右移50"anchors.bottom: parent.bottomonClicked: behaviorImg.x += 50}}
}
代码说明:
- Behavior on x声明x坐标的默认动画行为
- NumberAnimation用于实现数值动画
- OutBounce缓动效果用于实现弹性动画
- 按钮直接修改x值,同时会触发Behavior中的NumberAnimation动画。
运行效果:
- 点击"左移"按钮:表情包向左侧移动50(带弹跳效果)
- 点击"右移"按钮:表情包向右侧移动50(带弹跳效果)
示例3:预定义动画
PredefinedAnimation.qml
import QtQuick
import QtQuick.ControlsRectangle {width: 400height: 400AnimatedImage {id: imgsource: "qrc:/images/rotation.gif"x: 150y: 150width: 150height: 148// 预定义动画NumberAnimation {id: predefAnimtarget: imgproperties: "rotation"to: 360duration: 500onStopped: {to = to===360 ? 0 : 360}}}Button {text: "启动预定义动画"anchors.bottom: parent.bottomonClicked: {if (predefAnim.running) return;predefAnim.start();}}
}
代码说明:
- 独立定义的NumberAnimation动画对象
- 显式指定target和properties
- 设置旋转角度目标值360度,动画执行时间为500ms
- 动画停止时重置目标值实现循环旋转
运行效果:
- 点击按钮后:箭头图片开始顺时针旋转
- 单次动画完成360度旋转耗时500ms
- 连续点击可实现连续旋转效果
总结
通过三个动画示例,我们可以得出以下结论:
- PropertyAnimation适合精确控制单个属性的动画过程、
- Behavior机制可实现属性变化的自动动画过渡
- 预定义动画对象便于复用复杂动画配置
工程下载
Gitcode仓库地址: GitCode -> QML Animation示例
(包含完整源码和资源文件)