使用Qt實現旋轉動畫效果
更新時間:2024年11月19日 11:16:50 作者:姆路
這篇文章主要為大家詳細介紹了如何使用Qt實現旋轉動畫效果,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
使用QPropertyAnimation類綁定對應的屬性后
就可以給這個屬性設置對應的動畫
//比如自定義了屬性 Q_PROPERTY(int rotation READ rotation WRITE setRotation) //給這個屬性加動畫效果 //參數1:誰要加動畫效果 //參數2:哪個屬性加動畫效果 //參數3:parent m_animation = new QPropertyAnimation(this, "rotation", this); m_animation -> setDuration(2000); //設置動畫時長 m_animation -> setStartValue(0); //設置開始值 m_animation -> setEndValue(360); //設置結束值 m_animation -> setLoopCount(3); //設置循環(huán)次數 m_animation -> start(); //開啟動畫
動畫開啟后,就會不停的調用setRotation(屬性write函數)去修改這個屬性的值
我們在setRotation這個函數中修改屬性的值后,調用update()
于是QPropertyAnimation就會使得對應的控件不停的重繪,就產生了動畫效果。
舉例:
旋轉的矩形

完整代碼
#ifndef WIDGET_H
#define WIDGET_H
#include<QPropertyAnimation>
#include<QPainter>
#include <QWidget>
class RotatingWidget : public QWidget {
Q_OBJECT
//QPropertyAnimation類要搭配Q_PROPERTY定義的屬性來使用
//本質上就是QPropertyAnimation在不停的修改對應屬性的值,然后不停的重繪,看起來像動的效果
Q_PROPERTY(int rotation READ rotation WRITE setRotation)
public:
RotatingWidget(QWidget *parent = nullptr): QWidget(parent), m_rotation(0) {
m_animation = new QPropertyAnimation(this, "rotation", this);
m_animation->setDuration(2000);//設置動畫時長
m_animation->setStartValue(0);//設置開始值
m_animation->setEndValue(360);//設置結束值
m_animation->setLoopCount(3);//設置循環(huán)次數
//還可以設置動畫的效果曲線,是勻速還是先快后慢等
m_animation->start();//開啟動畫
}
int rotation() const {
return m_rotation;
}
public slots:
void setRotation(int angle) {
m_rotation = angle;
//屬性修改后就進行重繪
update();
}
protected:
void paintEvent(QPaintEvent *event) override {
QWidget::paintEvent(event);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(width() / 2, height() / 2);
painter.rotate(m_rotation);
painter.translate(-width() / 2, -height() / 2);
// 繪制旋轉的圖形,也可以是圖片
painter.setPen(QPen(Qt::red));
painter.drawRect(width() / 2-50, height() / 2-50, 100, 100);
}
private:
QPropertyAnimation *m_animation;
int m_rotation;
};
#endif // WIDGET_H到此這篇關于使用Qt實現旋轉動畫效果的文章就介紹到這了,更多相關Qt旋轉動畫內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

