使用Qt實現(xiàn)旋轉(zhuǎn)動畫效果
使用QPropertyAnimation類綁定對應的屬性后
就可以給這個屬性設(shè)置對應的動畫
//比如自定義了屬性 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就會使得對應的控件不停的重繪,就產(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在不停的修改對應屬性的值,然后不停的重繪,看起來像動的效果
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;
//屬性修改后就進行重繪
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)文章
排列組合總結(jié):將結(jié)果進行輸出的實現(xiàn)方法
本篇文章關(guān)于排列組合的總結(jié),對結(jié)果進行輸出做了介紹。需要的朋友參考下2013-05-05
使用C++開發(fā)一個串口讀寫軟件的實現(xiàn)步驟
這篇文章主要介紹了使用xmake(一個項目管理工具兼包管理工具)和asio2(一個asio的框架,可以實現(xiàn)輕松各種網(wǎng)絡應用,一般支持tcp,udp,http,websocket,rpc,ssl,icmp,serial_port.)來快速的開發(fā)個串口讀寫軟件(整合例程),需要的朋友可以參考下2025-04-04

