1、QWidget的QPropertyAnimation漸隐動畫
顯隐是動畫效果裡比較常見的,一定要學會喲。
A、一般顯隐動畫:
雖然說QWidget沒有opacity屬性,但是卻有windowOpacity屬性。
上代碼:
#include <QPropertyAnimation>
QPropertyAnimation *m_animation;
m_animation = new QPropertyAnimation(this, "windowOpacity");
m_animation->setStartValue(1);
m_animation->setEndValue(0);
m_animation->setDuration(1000);
m_animation->setEasingCurve(QEasingCurve::Linear);//動畫效果
connect(m_animation, SIGNAL(finished()), this, SLOT(onAnimation()));//做了簡單的處理,這個槽是根據需要寫的
B、特殊情況:
有時,我們會遇到特殊情況,特别是和QGraphics體系混編的時候,有時如上述所做是不能解決問題的。
QGraphics體系裡面顯隐屬性opacity,下面給出新的解決方案:
上代碼:
#include <QGraphicsOpacityEffect>
#include <QPropertyAnimation>
QPropertyAnimation *m_animation;
QGraphicsOpacityEffect* m_widgetOpacity;
m_widgetOpacity = new QGraphicsOpacityEffect(this);
m_widgetOpacity->setOpacity(1.0);
this->setGraphicsEffect(m_widgetOpacity);
m_animation = new QPropertyAnimation(m_widgetOpacity,"opacity",this);
m_animation->setStartValue(1);
m_animation->setEndValue(0);
m_animation->setDuration(1000);
m_animation->setEasingCurve(QEasingCurve::Linear);//動畫效果
connect(m_animation, SIGNAL(finished()), this, SLOT(onAnimation()));
2、QML PropertyAnimation在動畫執行完做其它事
主要調用ParallelAnimation的onStopped方法:
看示例代碼:
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
visible: true
width: 800
height: 600
Rectangle {
id: rect
anchors.fill: parent
color: "red"
MouseArea {
anchors.fill: parent
onClicked: pro.start()
}
}
PropertyAnimation {
id:pro
target: rect
properties: "color";
to: "green";
duration: 1000
onStopped: console.log("log pro")
}
}
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
visible: true
Rectangle {
id: rect
anchors.fill: parent
state: "state_green"
MouseArea { anchors.fill: parent
onClicked: con.start()
}
states: [
State {id: st1;name: "state_green"; PropertyChanges {target: rect;color: "green";}},
State {id: st2;name: "state_blue"; PropertyChanges {target: rect;color: "blue";}}
]
transitions: [
Transition {
from: "state_green"
to: "state_blue"
PropertyAnimation{
id: pro_green
target: rect; property: "color"; duration: 1000;
}
},
Transition {
from: "state_blue"
to: "state_green"
PropertyAnimation{
id: pro_blue
target: rect; property: "color"; duration: 1000;
}
}
]
PropertyAnimation{
id:con
duration: 1000;
onStarted: (rect.state=="state_green")?(rect.state = "state_blue"):(rect.state = "state_green")
onStopped: {
if(rect.state == "state_blue") {
console.log("state_blue")
} else {
console.log("state_green")
}
}
}
}
}