版本:Qt 6.5.1
动画的创建方式
1. 属性
从属性中设置动画,让动画作为属性值的来源。
语法:动画 on 属性
① 属性动画
import QtQuick 2.3
Window
{
visible: true; width: 640; height: 480; title: qsTr("Hello World")
Rectangle
{
width: 200; height: 200; color: "pink"
// 属性动画:x方向上的动画
PropertyAnimation on x
{
to: 50
duration: 1000
loops: Animation.Infinite // 循环动画效果
easing.type: Easing.OutBounce // 设置缓和曲线为:end位置回弹
}
// 属性动画:y方向上的动画
PropertyAnimation on y
{
to: 200
duration: 1000
loops: Animation.Infinite
easing.type: Easing.OutBounce
}
} // Rectangle end
} // Window end
② 颜色动画、旋转动画
import QtQuick 2.3
Window
{
visible: true; width: 640; height: 480; title: qsTr("Hello World")
Rectangle
{
width: 200; height: 200
// 颜色渐变
ColorAnimation on color
{
from: "pink"
to: "gray"
duration: 1500
}
// 旋转
RotationAnimation on rotation
{
to: 90
duration: 1000
direction: RotationAnimation.Clockwise
}
} // Rectangle end
} // Window end
2. 行为 (Behavior)
行为动画,以 Behavior 为一个属性值来指定默认动画。
语法:Behavior on 属性
import QtQuick 2.3
Window
{
visible: true; width: 640; height: 480; title: qsTr("Hello World")
Rectangle
{
id: rect
width: 200; height: 200; color: "pink"
// 为x添加举动
Behavior on x
{
PropertyAnimation
{
duration: 1000
// 可以设置loops、easing...
}
}
Behavior on y
{
PropertyAnimation
{
duration: 1000
}
}
MouseArea
{
anchors.fill: parent
onClicked:
{
rect.x = 50
rect.y = 200
}
}
} // Rectagle end
} // Window end
3. 信号处理器
这里的例子是利用鼠标点击释放的信号,在 MouseArea 中使用处理点击信号的 onClick,进行动画设置。
import QtQuick 2.3
Window
{
visible: true; width: 640; height: 480; title: qsTr("Hello World")
Rectangle
{
id: rect
width: 200; height: 200; color: "pink"
MouseArea
{
anchors.fill: parent
onClicked: PropertyAnimation
{
target: rect
properties: "x, y"
to: 100
duration:1000
}
}
} // Rectagle end
} // Window end
4. 动画对象
动画本身作为一个对象,使用的时候调取。
import QtQuick 2.3
Window
{
visible: true; width: 640; height: 480; title: qsTr("Hello World")
Rectangle
{
id: rect
width: 200; height: 200; color: "pink"
anchors.left: undefined
// 属性动画
PropertyAnimation
{
id: animatione_x
target: rect
properties: "x"
duration: 200
}
PropertyAnimation
{
id: animatione_y
target: rect
properties: "y"
duration: 100
}
MouseArea
{
anchors.fill: parent
onClicked:
{
animatione_x.to = 200
animatione_x.running = true
animatione_y.to = 100
animatione_y.running = true
}
}
} // Rectagle end
} // Window end
动画的状态切换
本例子的状态转换根据鼠标的点击释放进行变换
import QtQuick 2.3
Window
{
visible: true; width: 640; height: 480; title: qsTr("Hello World")
Rectangle
{
id: rect
width: 200; height: 200; color: "pink"
MouseArea
{
anchors.fill: parent
onClicked: // 鼠标点击时调1状态
{
rect.state = "moved_1"
}
onReleased: // 鼠标释放时调2状态
{
rect.state = "moved_2"
}
}
// 状态列表
// states:[State{}, State{}]
states: [
State
{
name: "moved_1"
PropertyChanges
{
target: rect
x: 50; y: 100
}
},
State
{
name: "moved_2"
PropertyChanges
{
target: rect
x: 100; y: 50
}
}
]
transitions: Transition
{
PropertyAnimation
{
properties: "x, y"
duration: 1000
}
}
}// Rectangle end
} // Window end