使用Qt實現(xiàn)旋轉(zhuǎn)動畫效果
使用QPropertyAnimation類綁定對應(yīng)的屬性后
就可以給這個屬性設(shè)置對應(yīng)的動畫
//比如自定義了屬性 Q_PROPERTY(int rotation READ rotation WRITE setRotation) //給這個屬性加動畫效果 //參數(shù)1:誰要加動畫效果 //參數(shù)2:哪個屬性加動畫效果 //參數(shù)3:parent m_animation = new QPropertyAnimation(this, "rotation", this); m_animation -> setDuration(2000); //設(shè)置動畫時長 m_animation -> setStartValue(0); //設(shè)置開始值 m_animation -> setEndValue(360); //設(shè)置結(jié)束值 m_animation -> setLoopCount(3); //設(shè)置循環(huán)次數(shù) m_animation -> start(); //開啟動畫
動畫開啟后,就會不停的調(diào)用setRotation(屬性write函數(shù))去修改這個屬性的值
我們在setRotation這個函數(shù)中修改屬性的值后,調(diào)用update()
于是QPropertyAnimation就會使得對應(yīng)的控件不停的重繪,就產(chǎn)生了動畫效果。
舉例:
旋轉(zhuǎn)的矩形

完整代碼
#ifndef WIDGET_H
#define WIDGET_H
#include<QPropertyAnimation>
#include<QPainter>
#include <QWidget>
class RotatingWidget : public QWidget {
Q_OBJECT
//QPropertyAnimation類要搭配Q_PROPERTY定義的屬性來使用
//本質(zhì)上就是QPropertyAnimation在不停的修改對應(yīng)屬性的值,然后不停的重繪,看起來像動的效果
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);//設(shè)置動畫時長
m_animation->setStartValue(0);//設(shè)置開始值
m_animation->setEndValue(360);//設(shè)置結(jié)束值
m_animation->setLoopCount(3);//設(shè)置循環(huán)次數(shù)
//還可以設(shè)置動畫的效果曲線,是勻速還是先快后慢等
m_animation->start();//開啟動畫
}
int rotation() const {
return m_rotation;
}
public slots:
void setRotation(int angle) {
m_rotation = angle;
//屬性修改后就進(jìn)行重繪
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);
// 繪制旋轉(zhuǎn)的圖形,也可以是圖片
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到此這篇關(guān)于使用Qt實現(xiàn)旋轉(zhuǎn)動畫效果的文章就介紹到這了,更多相關(guān)Qt旋轉(zhuǎn)動畫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++?Protobuf實現(xiàn)接口參數(shù)自動校驗詳解
用C++做業(yè)務(wù)發(fā)開的同學(xué)是否還在不厭其煩的編寫大量if-else模塊來做接口參數(shù)校驗?zāi)??今天,我們就模擬Java里面通過注解實現(xiàn)參數(shù)校驗的方式來針對C++?protobuf接口實現(xiàn)一個更加方便、快捷的參數(shù)校驗自動工具,希望對大家有所幫助2023-04-04
詳解C語言中telldir()函數(shù)和seekdir()函數(shù)的用法
這篇文章主要介紹了詳解C語言中telldir()函數(shù)和seekdir()函數(shù)的用法,是C語言入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09
C語言 數(shù)據(jù)結(jié)構(gòu)與算法之字符串詳解
這篇文章將帶大家深入了解C語言數(shù)據(jù)結(jié)構(gòu)與算法中的字符串,文中主要是介紹了字符串的定義、字符串的比較以及一些串的抽象數(shù)據(jù)類型,感興趣的可以學(xué)習(xí)一下2022-01-01

