使用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旋转动画内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
            
                                            
                                            
                                            
                                            
                                            
发表评论