添加qml文件AnimationItem.qml
以下是AnimationItem.qml文件内容
这里写代码片
import QtQuick 2.0
Item {
id: root
property bool show: false
property real showPropertyChangeOpacity: 1
property real showPropertyChangeX: 0
property real showPropertyChangeY: 0
property real showPropertyChangeZ: 1
property real hidePropertyChangeOpacity: 0
property real hidePropertyChangeX: 0
property real hidePropertyChangeY: root.height/1.3
property real hidePropertyChangeZ: 0
state: "hide"
states: [
State {
name: "show"
PropertyChanges {
target: root
opacity: showPropertyChangeOpacity
x: showPropertyChangeX
y: showPropertyChangeY
z: showPropertyChangeZ
}
when: show
},
State {
name: "hide"
PropertyChanges {
target: root
opacity: hidePropertyChangeOpacity
x: hidePropertyChangeX
y: hidePropertyChangeY
z: hidePropertyChangeZ
}
when: !show
}
]
transitions: Transition {
onRunningChanged:{
if(running == true && show){
root.visible = true
}
if(running == false && !show){
root.visible = false
}
}
NumberAnimation{properties: "x,y"; easing.type: Easing.InOutQuad; duration: 300}
NumberAnimation{properties: "opacity"; easing.type: Easing.InOutQuad; duration: 300}
}
}
要想页面能有动画效果,只需继承AnimationItem,简单来说就是把页面的内容加到AnimationItem控件中即可,下面会有示例.
稍微解析一下这个AnimationItem,其实很简单,就是一个页面两个状态,显示和隐藏状态,当隐藏一个页面显示另外一个页面这个过渡过程使用Transition实现就显示出页面切换的动画效果(Transition的作用是把状态直接切换改成一个过渡切换的过程,过渡切换页面显示的是一个动画过程)
页面切换的实质就是y坐标和透明度opacity的变化,呈现的是一个页面上下滑动的过程.
自定义两个页面,PageOne.qml表示第一个页面,PageTwo.qml表示第二个页面
一切简单化处理PageOne.qml文件内容如下:
AnimationItem {
id: root
Rectangle{
anchors.fill: parent
color: "green"
}
}
PageTwo.qml文件内容如下:
AnimationItem {
id: root
Rectangle{
anchors.fill: parent
color: "yellow"
}
}
main.qml文件内容如下:
Window {
visible: true
width: 640
height: 480
title: qsTr("Animation Test")
property int pageIndex: 1
PageOne {
width: parent.width
height: parent.height
show: pageIndex===1
}
PageTwo {
width: parent.width
height: parent.height
show: pageIndex===2
}
MouseArea{
anchors.fill: parent
onClicked: {
if(pageIndex===1){pageIndex=2}
else{pageIndex=1}
}
}
}
点击页面就能进行两个页面之间的动画切换了.
需要注意的是PageOne,PageTwo或者继承AnimationItem的页面不是使用锚(anchors布局)布局,因为如果使用锚布局这个页面的y值就不能动了,会导致页面移动的动画效果消失