使用Qt實(shí)現(xiàn)旋轉(zhuǎn)動(dòng)畫效果
使用QPropertyAnimation類綁定對(duì)應(yīng)的屬性后
就可以給這個(gè)屬性設(shè)置對(duì)應(yīng)的動(dòng)畫
//比如自定義了屬性 Q_PROPERTY(int rotation READ rotation WRITE setRotation) //給這個(gè)屬性加動(dòng)畫效果 //參數(shù)1:誰(shuí)要加動(dòng)畫效果 //參數(shù)2:哪個(gè)屬性加動(dòng)畫效果 //參數(shù)3:parent m_animation = new QPropertyAnimation(this, "rotation", this); m_animation -> setDuration(2000); //設(shè)置動(dòng)畫時(shí)長(zhǎng) m_animation -> setStartValue(0); //設(shè)置開始值 m_animation -> setEndValue(360); //設(shè)置結(jié)束值 m_animation -> setLoopCount(3); //設(shè)置循環(huán)次數(shù) m_animation -> start(); //開啟動(dòng)畫
動(dòng)畫開啟后,就會(huì)不停的調(diào)用setRotation(屬性write函數(shù))去修改這個(gè)屬性的值
我們?cè)趕etRotation這個(gè)函數(shù)中修改屬性的值后,調(diào)用update()
于是QPropertyAnimation就會(huì)使得對(duì)應(yīng)的控件不停的重繪,就產(chǎn)生了動(dòng)畫效果。
舉例:
旋轉(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在不停的修改對(duì)應(yīng)屬性的值,然后不停的重繪,看起來像動(dò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è)置動(dòng)畫時(shí)長(zhǎng) m_animation->setStartValue(0);//設(shè)置開始值 m_animation->setEndValue(360);//設(shè)置結(jié)束值 m_animation->setLoopCount(3);//設(shè)置循環(huán)次數(shù) //還可以設(shè)置動(dòng)畫的效果曲線,是勻速還是先快后慢等 m_animation->start();//開啟動(dòng)畫 } 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實(shí)現(xiàn)旋轉(zhuǎn)動(dòng)畫效果的文章就介紹到這了,更多相關(guān)Qt旋轉(zhuǎn)動(dòng)畫內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
排列組合總結(jié):將結(jié)果進(jìn)行輸出的實(shí)現(xiàn)方法
本篇文章關(guān)于排列組合的總結(jié),對(duì)結(jié)果進(jìn)行輸出做了介紹。需要的朋友參考下2013-05-05C++實(shí)現(xiàn)稀疏矩陣的壓縮存儲(chǔ)實(shí)例
本篇文章主要介紹了C++實(shí)現(xiàn)稀疏矩陣的壓縮存儲(chǔ)實(shí)例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06使用C++開發(fā)一個(gè)串口讀寫軟件的實(shí)現(xiàn)步驟
這篇文章主要介紹了使用xmake(一個(gè)項(xiàng)目管理工具兼包管理工具)和asio2(一個(gè)asio的框架,可以實(shí)現(xiàn)輕松各種網(wǎng)絡(luò)應(yīng)用,一般支持tcp,udp,http,websocket,rpc,ssl,icmp,serial_port.)來快速的開發(fā)個(gè)串口讀寫軟件(整合例程),需要的朋友可以參考下2025-04-04