当前位置: 代码网 > it编程>编程语言>C/C++ > 使用Qt实现旋转动画效果

使用Qt实现旋转动画效果

2024年11月20日 C/C++ 我要评论
使用qpropertyanimation类绑定对应的属性后就可以给这个属性设置对应的动画//比如自定义了属性q_property(int rotation read rotation write se

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

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

//比如自定义了属性
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就会使得对应的控件不停的重绘,就产生了动画效果。

举例:

旋转的矩形

完整代码 

#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

到此这篇关于使用qt实现旋转动画效果的文章就介绍到这了,更多相关qt旋转动画内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com