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
相关推荐
??tobenewyorker1 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
oioihoii2 小时前
C++11 forward_list 从基础到精通:原理、实践与性能优化
c++·性能优化·list
m0_687399842 小时前
写一个Ununtu C++ 程序,调用ffmpeg API, 来判断一个数字电影的视频文件mxf 是不是Jpeg2000?
开发语言·c++·ffmpeg
看到我,请让我去学习3 小时前
Qt编程-qml操作(js,c++,canvas)
开发语言·qt
Ronin3054 小时前
【C++】类型转换
开发语言·c++
mrbone114 小时前
Git-git worktree的使用
开发语言·c++·git·cmake·worktree·gitab
哈市雪花4 小时前
相机:Camera原理讲解(使用OpenGL+QT开发三维CAD)
qt·3d·交互·相机·图形学·opengl·视角
虾球xz5 小时前
CppCon 2018 学习:EFFECTIVE REPLACEMENT OF DYNAMIC POLYMORPHISM WITH std::variant
开发语言·c++·学习
津津有味道6 小时前
Qt C++串口SerialPort通讯发送指令读写NFC M1卡
linux·c++·qt·串口通信·serial·m1·nfc
让我们一起加油好吗7 小时前
【C++】list 简介与模拟实现(详解)
开发语言·c++·visualstudio·stl·list