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
相关推荐
DYS_房东的猫16 分钟前
写出第一个程序
c++
ulias21218 分钟前
AVL树的实现
开发语言·数据结构·c++·windows
cn_mengbei20 分钟前
鸿蒙PC开发指南:从零配置Qt环境到实战部署完整流程
qt·华为·harmonyos
山上三树21 分钟前
详细介绍 C/C++ 中的内存泄漏
c语言·c++
GREGGXU25 分钟前
Could not load the Qt platform plugin “xcb“ in ““ even though it was found.
linux·qt
CSDN_RTKLIB27 分钟前
CMake构建目标核心命令
c++
郝学胜-神的一滴29 分钟前
图形学中的纹理映射问题:摩尔纹与毛刺的深度解析
c++·程序人生·unity·游戏引擎·图形渲染·unreal engine
Cx330❀1 小时前
【优选算法必刷100题】第43题(模拟):数青蛙
c++·算法·leetcode·面试
闻缺陷则喜何志丹1 小时前
【C++动态规划 状压dp】1879. 两个数组最小的异或值之和|2145
c++·算法·动态规划·力扣·数组·最小·动态规范
艾莉丝努力练剑1 小时前
【优选算法必刷100题:专题五】(位运算算法)第033~38题:判断字符是否唯一、丢失的数字、两整数之和、只出现一次的数字 II、消失的两个数字
java·大数据·运维·c++·人工智能·算法·位运算