zl程序教程

您现在的位置是:首页 >  工具

当前栏目

QT之QPropertyAnimation简单应用

Qt应用 简单
2023-09-14 09:07:10 时间

头文件:

#ifndef CPROPERTYANIMATIONTEST_H
#define CPROPERTYANIMATIONTEST_H

#include<QWidget>
#include<QPropertyAnimation>
#include <QParallelAnimationGroup>
class CPropertyAnimationTest:public QWidget
{
    Q_OBJECT
public:
    CPropertyAnimationTest(QWidget *parent=nullptr);

    QPropertyAnimation *m_animation;
    QPropertyAnimation *m_animation2;
    QAnimationGroup *m_animationGroup;
};

#endif // CPROPERTYANIMATIONTEST_H

源文件:

#include "cpropertyanimationtest.h"
#include<QPushButton>

CPropertyAnimationTest::CPropertyAnimationTest(QWidget *parent):QWidget(parent)
{
    resize(600,400);
    m_animationGroup = new QParallelAnimationGroup(this);

    QPushButton *btn=new QPushButton("0",this);
    btn->resize(60,30);

    QPushButton *btn2=new QPushButton("1",this);
    btn2->resize(60,30);
    btn2->move(btn->pos().x()+btn->width()+50,0);

    QPushButton *start=new QPushButton("开始",this);
    start->resize(60,30);
    start->move(0,height()-start->height());

    m_animation=new QPropertyAnimation;
    m_animation->setTargetObject(btn);
    m_animation->setPropertyName("pos");
    m_animation->setDuration(300);


    m_animation2=new QPropertyAnimation;
    m_animation2->setTargetObject(btn2);
    m_animation2->setPropertyName("pos");
    m_animation2->setDuration(300);


    m_animationGroup->addAnimation(m_animation);
    m_animationGroup->addAnimation(m_animation2);




    connect(start,&QPushButton::clicked,this,[=](){

        if(btn->pos().x()>width())
        {
            m_animation->setStartValue(QPoint(0,0));
            btn->move(QPoint(0,0));

        }
        else
            m_animation->setStartValue(btn->pos());
        m_animation->setEndValue(QPoint(btn->pos().x()+btn->width()+50,0));
        if((btn2->pos().x())>width())
        {
            m_animation2->setStartValue(QPoint(0,0));
            btn2->move(QPoint(0,0));

        }
        else
            m_animation2->setStartValue(btn2->pos());
        m_animation2->setEndValue(QPoint(btn2->pos().x()+btn2->width()+50,0));
        m_animationGroup->start();

    });

}