Qt之AnimationButton

本文介绍如何使用Qt和QTimer创建动画按钮,通过继承QPushButton并利用定时器改变按钮大小,实现鼠标悬停时的放大和离开时的缩小效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动画按钮

使用定时器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());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值