【QT】Qt QML動畫概述
阿新 • • 發佈:2019-01-28
QML提供了豐富的動畫元素,說起動畫,無非是給UI增光添彩罷了。在QML中,動畫常常與State和Transition聯絡在一起,這幾個概念(下面的例子中都用到了)都比較簡單,相關介紹可檢視Qt官方文件,網址如下:
下面先列舉幾個QML動畫元素,動畫效果可“忘文生意”:
PropertyAnimation(常用)
AnchorAnimation
ColorAnimation
NumberAnimation
ParentAnimation
PathAnimation
RotationAnimation
Vector3dAnimation
SequentialAnimation
ParalleAnimation
PauseAnimation
SmoothedAnimation
SpringAnimation
PropertyAction(無動畫效果)
ScriptAction
Behavior(設定預設動畫)
常見的QML動畫有三種表示方式,下面一一說明。
1、使用State和Transition
State改變屬性值,Transition實現動畫,例子如下:
import QtQuick 2.2 Item { id: container width: 360 height: 360 Rectangle { id: rect width: 100 height: 100 color: "blue" MouseArea { anchors.fill: parent // state屬性值為空字串時('')即預設狀態 onClicked: container.state == 'right' ? container.state = '' : container.state = 'right' } } states: State { name: "right" // rect水平移動 PropertyChanges { target: rect x: 260 } } transitions: Transition { // 數字(x座標)動畫,設定了easing的回彈效果和動畫時間 NumberAnimation { property: "x" easing.type: Easing.InOutBounce duration: 500 } } }
2、使用Behavior
直接修改上面的例子,實現同樣的動畫效果,結果如下:
import QtQuick 2.2 Item { id: container width: 360 height: 360 Rectangle { id: rect width: 100 height: 100 color: "blue" // 看這裡 Behavior on x { NumberAnimation { easing.type: Easing.InOutBounce duration: 500 } } MouseArea { anchors.fill: parent // 改變rect的x座標 onClicked: rect.x = (rect.x == 0 ? 260 : 0) } } }
3、其它
還是在上面例子的基礎上修改以實現同樣的效果,程式碼如下:
import QtQuick 2.2
Item {
id: container
width: 360
height: 360
Rectangle {
id: rect
width: 100
height: 100
color: "blue"
// rect水平右移
NumberAnimation on x {
id: right
running: false // false
to: 260
easing.type: Easing.InOutBounce
duration: 500
}
// rect水平左移
NumberAnimation on x {
id: left
running: false // false
to: 0
easing.type: Easing.OutInBounce // 換個easing動畫效果
duration: 500
}
MouseArea {
anchors.fill: parent
// 判斷移動方向
onClicked: rect.x == 0 ? right.running = true : left.running = true
}
}
}
下面再來看一個有意思的例子,parallel和sequential動畫:
import QtQuick 2.2
Item {
id: container
width: 360
height: 360
Rectangle {
id: up
width: 100
height: 100
color: "blue"
// 並行動畫,水平移動和顏色變化同時進行
ParallelAnimation {
id: parallel
running: false
PropertyAnimation {
target: up
property: "x"
to: 260
duration: 500
}
PropertyAnimation {
target: up
property: "color"
to: "red"
duration: 500
}
}
MouseArea {
anchors.fill: parent
onClicked: parallel.running = true
}
}
Rectangle {
id: down
width: 100
height: 100
color: "red"
anchors.top: up.bottom
// 序列動畫,先進行水平移動,後進行顏色變化
SequentialAnimation {
id: sequential
running: false
PropertyAnimation {
target: down
property: "x"
to: 260
duration: 500
}
PropertyAnimation {
target: down
property: "color"
to: "blue"
duration: 500
}
}
MouseArea {
anchors.fill: parent
onClicked: sequential.running = true
}
}
}
關於QML動畫,Qt官網文件也做了詳細的介紹: