QML中的transitions 过渡
在QML中,transitions用于定义动画效果,这些动画效果会在状态变化时自动触发
。状态变化通常由State和StateGroup定义。
Transition可以包含多个动画,例如PropertyAnimation、NumberAnimation等,用于在状态变化时对属性进行动画处理。
位置变化的过渡
import QtQuick 2.15
// 主矩形,宽200,高200,颜色为绿色
Rectangle {
width: 200
height: 200
color: "green"
// 内部矩形,初始位置在(0, 0),颜色为蓝色
Rectangle {
id: movingRect
width: 50
height: 50
color: "blue"
x: 0
y: 0
// 定义状态
states: [
State {
name: "movedState" // 状态名称
PropertyChanges {
target: movingRect; // 目标对象
x: 150; y: 150 // 将位置改为(150, 150)
}
}
]
// 定义过渡动画
transitions: [
Transition {
from: "*"; to: "movedState" // 从任意状态到"movedState"状态
NumberAnimation { properties: "x,y"; duration: 1000; easing.type: Easing.OutQuad } // 位置变化动画,持续1秒,缓动类型为OutQuad
}
]
// 鼠标区域,点击时改变状态
MouseArea {
anchors.fill: parent // 填充父对象
onClicked: movingRect.state = "movedState" // 点击时将状态改为"movedState"
}
}
}
旋转和缩放的过渡
import QtQuick 2.15
// 主矩形,宽200,高200,颜色为黄色
Rectangle {
width: 200
height: 200
color: "yellow"
// 内部矩形,初始位置在(75, 75),初始旋转角度为0,初始缩放比例为1,颜色为红色
Rectangle {
id: rotatingRect
width: 50
height: 50
color: "red"
x: 75
y: 75
rotation: 0
scale: 1
// 定义状态
states: [
State {
name: "rotatedState" // 状态名称
PropertyChanges {
target: rotatingRect; // 目标对象
rotation: 180; scale: 2 // 将旋转角度改为180度,缩放比例改为2
}
}
]
// 定义过渡动画
transitions: [
Transition {
from: "*"; to: "rotatedState" // 从任意状态到"rotatedState"状态
NumberAnimation { properties: "rotation"; duration: 1000; easing.type: Easing.InOutQuad } // 旋转动画,持续1秒,缓动类型为InOutQuad
NumberAnimation { properties: "scale"; duration: 1000; easing.type: Easing.InOutQuad } // 缩放动画,持续1秒,缓动类型为InOutQuad
}
]
// 鼠标区域,点击时改变状态
MouseArea {
anchors.fill: parent // 填充父对象
onClicked: rotatingRect.state = "rotatedState" // 点击时将状态改为"rotatedState"
}
}
}
复杂的多属性过渡
import QtQuick 2.15
// 主矩形,宽200,高200,颜色为浅蓝色
Rectangle {
width: 200
height: 200
color: "lightblue"
// 内部矩形,初始位置在(0, 0),初始旋转角度为0,初始缩放比例为1,颜色为绿色
Rectangle {
id: complexRect
width: 50
height: 50
color: "green"
x: 0
y: 0
rotation: 0// 初始旋转角度为0
scale: 1 // 初始缩放比例为1
// 定义状态
states: [
State {
name: "complexState" // 状态名称
PropertyChanges {
target: complexRect; // 目标对象
x: 150; y: 150; rotation: 360; scale: 0.5; color: "blue" // 将位置改为(150, 150),旋转角度改为360度,缩放比例改为0.5,颜色改为蓝色
}
}
]
// 定义过渡动画
transitions: [
Transition {
from: "*"; to: "complexState" // 从任意状态到"complexState"状态
NumberAnimation { properties: "x,y"; duration: 1000; easing.type: Easing.OutQuad } // 位置变化动画,持续1秒,缓动类型为OutQuad
NumberAnimation { properties: "rotation"; duration: 1000; easing.type: Easing.InOutQuad } // 旋转动画,持续1秒,缓动类型为InOutQuad
NumberAnimation { properties: "scale"; duration: 1000; easing.type: Easing.InOutQuad } // 缩放动画,持续1秒,缓动类型为InOutQuad
ColorAnimation { duration: 1000 } // 颜色变化动画,持续1秒
}
]
// 鼠标区域,点击时改变状态
MouseArea {
anchors.fill: parent // 填充父对象
onClicked: complexRect.state = "complexState" // 点击时将状态改为"complexState"
}
}
}