QML 动画简单说明
Transition 是一种比较强大动画执行类,适合较为复杂的动画操作(内部动画,默认是并行 ParallelAnimation)
Behavior 则是一种比较简单动画执行类,默认一个 Behavior 只能对一个属性做出改变,如果要多个动画执行则需要通过 SequentialAnimation 和 ParallelAnimation
info: Transition 内容
Rectangle {
id: rect
width: 100; height: 100
color: "red"
MouseArea {
id: mouseArea
anchors.fill: parent
}
states: State {
name: "moved"; when: mouseArea.pressed
PropertyChanges {target: rect; x: 50; y: 50}
}
//单个
transitions: Transition {
PropetyAnimation { properties: "x,y"; easing.type: Easing.InOutQuad}
}
/* //多个
transitions: [
Transition { //使用 Transition 最好明确声明 from to 属性以确保可读性和避免隐形转换可能产生的问题
from: "moved"/单个 Transition 可以隐藏
to: "moved"//单个 Transition 可以隐藏
PropetyAnimation { properties: "x,y"; easing.type: Easing.InOutQuad}//easing.type 是指变化速度的曲线
//InOutQuad 运行过程是先加速,后减速
},
Transition {
}
]
*/
}
info: behavior 例子
Rectangle {
id: rect
width: 100; height: 100
color: "red"
Behavior on width {
NumberAnimation { duration: 1000 }
}
MouseArea {
anchors.fill: parent
onClicked: rect.width = 50
}
}
动画类型
1 AnchorAnimation 适用于 anchor
2 ColorAnimation 适用于 color
3 NumberAnimation 适用于一些与数字相关的比如 width\height\x\y 等
4 ParentAnimation 适用于 子类修改父类的参数,还是会使用上述 3 个类型
5 PathAnimation 适用于移动的时候没有定义起始和结束点,使用这个指定
6 PropertyAnimation 修改属性
7 RotationAnimation 旋转动画
8 Vector3dAnimation 适用于 QVector3d
动画的执行类
1 Transition 适用于复杂的变化
2 SequentialAnimation 顺序执行动画
3 ParallelAnimation 并行执行动画
4 Behavior 指定一个属性进行动画变化(默认只能一个属性)
5 PropertyAction 如果某些属性不具备动画特性,再执行前加上这句话,看 demo
6 PauseAnimation 暂停多长时间
7 SmoothedAnimation 匀速变化(可以设置时间)
8 SpringAnimation 弹簧效果,就是会有类似过冲等特效
9 ScriptAction 运行脚本
//info:PropertyAction official demo
Item {
width: 400; height: 400
Rectangle {
id: rect; width: 200; height: 200
color: "red"
states: State {
name: "rotated"
PropertyChanges {target: rect; rotation: 180; transformOrigin: Item.BottomRight}
}
transitions: Transition {
SequentialAnimation { //因为 Transition 默认是并行执行
PropertyAction { target: rect; property: "transformOrigin" }
RotationAnimation {duration: 1000; direction: RotationAnimation.Counterclockwise}
}
}
}
}
问题: 使用 Behavior 结果动画没法复原,比如红色变绿色,但最后没法从绿色变会红色
根据官方文档说明,这是属于 QML 存在的一个问题,当 Behavior 属性和 State 内定义的属性有相同的时候,可能会让 QML 陷入 snapshot 就是快照模式
官方说明检索:Using Qt Quick Behaviors with States
Behavior on color {
ColorAnimation {}
}
stats: State {
name: "GreenState"
when:mouser.containsMouse
PropertyChanges {
target: coloredRect; color: "green"
}
}
解决方式一:使用 Transition 代替 Behavior
解决方式二:使用类似 color: mousr.containsMouse ? “green” : “red”
解决方式三:在 state 里明确声明比如 when: mouser.contiansMouse / when:!mousr.contiansMouse