Qt中实现旋转动画效果

使用QPropertyAnimation类绑定对应的属性后

就可以给这个属性设置对应的动画

cpp 复制代码
//比如自定义了属性
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); //设置循环次数
m_animation -> start(); //开启动画

动画开启后,就会不停的调用setRotation(属性write函数)去修改这个属性的值

我们在setRotation这个函数中修改属性的值后,调用update()

于是QPropertyAnimation就会使得对应的控件不停的重绘,就产生了动画效果。

举例:

旋转的矩形

cpp 复制代码
#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);//设置循环次数
        //还可以设置动画的效果曲线,是匀速还是先快后慢等
        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
相关推荐
刚入门的大一新生11 分钟前
C++初阶-string类的模拟实现与改进
开发语言·c++
小冯的编程学习之路35 分钟前
【软件测试】:推荐一些接口与自动化测试学习练习网站(API测试与自动化学习全攻略)
c++·selenium·测试工具·jmeter·自动化·测试用例·postman
C++ 老炮儿的技术栈2 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
猪八戒1.02 小时前
C++ 回调函数和Lambda表达式
c++
源远流长jerry3 小时前
匿名函数lambda、STL与正则表达式
c++
tan180°4 小时前
Linux进程信号处理(26)
linux·c++·vscode·后端·信号处理
一只鱼^_4 小时前
牛客练习赛138(首篇万字题解???)
数据结构·c++·算法·贪心算法·动态规划·广度优先·图搜索算法
李匠20244 小时前
C++GO语言微服务之Dockerfile && docker-compose②
c++·容器
名誉寒冰4 小时前
# KVstorageBaseRaft-cpp 项目 RPC 模块源码学习
qt·学习·rpc
2301_803554525 小时前
c++和c的不同
java·c语言·c++