Qt之AnimationButton
动画按钮
使用定时器QTimer继承QPushButton来实现动画按钮
环境
Qt5.6.2+Vs2013
效果
代码
QAnimationButton类
AnimationButton.h
#ifndef ANIMATIONBUTTON_H
#define ANIMATIONBUTTON_H
#include <QPushButton>
#include <QTimer>
class QAnimationButton : public QPushButton
{
Q_OBJECT
public:
explicit QAnimationButton(QWidget *parent = nullptr);
~QAnimationButton();
protected:
void enterEvent(QEvent *event);
void leaveEvent(QEvent *event);
private slots:
void slot_timeout();
private:
QTimer* x_pTimer;
int x_nCurrentCnt;
enum AnimationDirect
{
UnKnow = 0,
Big,
Small
};
AnimationDirect x_emAnimation;
};
#endif // ANIMATIONBUTTON_H
AnimationButton.cpp
#include "AnimationButton.h"
#define STEP 5
#define STEPCOUNT 10
QAnimationButton::QAnimationButton(QWidget *parent)
: QPushButton(parent)
, x_pTimer(nullptr)
, x_nCurrentCnt(0)
{
x_emAnimation = UnKnow;
x_pTimer = new QTimer();
x_pTimer->setInterval(100);
connect(x_pTimer, SIGNAL(timeout()), this, SLOT(slot_timeout()));
}
QAnimationButton::~QAnimationButton()
{
if (x_pTimer)
{
if (x_pTimer->isActive())
{
x_pTimer->stop();
}
delete x_pTimer;
x_pTimer = nullptr;
}
}
void QAnimationButton::enterEvent(QEvent *event)
{
x_emAnimation = Big;
if (x_pTimer->isActive())
{
x_pTimer->stop();
}
x_pTimer->start();
}
void QAnimationButton::leaveEvent(QEvent *event)
{
x_emAnimation = Small;
if (x_pTimer->isActive())
{
x_pTimer->stop();
}
x_pTimer->start();
}
void QAnimationButton::slot_timeout()
{
QRect _rect = this->geometry();
if (x_emAnimation == Big)
{
if (x_nCurrentCnt >=0 && x_nCurrentCnt < STEPCOUNT)
{
x_nCurrentCnt++;
QRect _newRect = QRect(_rect.left() - STEP, _rect.top() - STEP, _rect.width() + 2 * STEP, _rect.height() + 2 * STEP);
this->setGeometry(_newRect);
}
else
{
x_pTimer->stop();
}
}
else if (x_emAnimation == Small)
{
if (x_nCurrentCnt > 0 && x_nCurrentCnt <= STEPCOUNT)
{
x_nCurrentCnt--;
QRect _newRect = QRect(_rect.left() + STEP, _rect.top() + STEP, _rect.width() - 2 * STEP, _rect.height() - 2 * STEP);
this->setGeometry(_newRect);
}
else
{
x_pTimer->stop();
}
}
}
使用
x_pAnimationButton = new QAnimationButton(this);
// 添加背景图
// x_pAnimationButton->setStyleSheet("QPushButton {"
// "border-image:url(':/image/Qt');}");
x_pAnimationButton->move(this->geometry().center());