Qt自定义button事件

直接上代码TPPPushButton.h

#include <QPushButton>
#include <QPainter>
#include <QMouseEvent>

class TPPPushButton :
	public QPushButton
{
public:
    explicit TPPPushButton(QWidget *parent = 0);
    ~TPPPushButton();
	void setPicName(QString pic_name);

protected:
	void enterEvent(QEvent *);
	void leaveEvent(QEvent *);
	void mousePressEvent(QMouseEvent *event);
	void mouseReleaseEvent(QMouseEvent *event);
	void paintEvent(QPaintEvent *);
private:
	// 枚举按钮的几种状态
	enum ButtonStatus { NORMAL, ENTER, PRESS, NOSTATUS };
	ButtonStatus status;
	QString pic_name;

	int btn_width;    // 按钮宽度
	int btn_height;   // 按钮高度
	bool mouse_press; // 按钮左键是否按下
};

TPPPushButton.cpp 

#include "TPPPushButton.h"


TPPPushButton::TPPPushButton(QWidget *parent) :
	QPushButton(parent)
{
	status = NORMAL;
	mouse_press = false;
}


TPPPushButton::~TPPPushButton()
{
}

void TPPPushButton::setPicName(QString pic_name)
{
	this->pic_name = pic_name;
	setFixedSize(QPixmap(pic_name).size());
}

void TPPPushButton::enterEvent(QEvent *)
{
	status = ENTER;
	update();
}

void TPPPushButton::leaveEvent(QEvent *)
{
    status = NORMAL;
    update();
}

void TPPPushButton::mousePressEvent(QMouseEvent *event)
{
	// 若点击鼠标左键
	if (event->button() == Qt::LeftButton)
	{
		mouse_press = true;
		status = PRESS;
		update();
	}
}


void TPPPushButton::mouseReleaseEvent(QMouseEvent *event)
{
	// 若点击鼠标左键
    if (mouse_press && this->rect().contains(event->pos()))
	{
		mouse_press = false;
		status = ENTER;
		update();
		emit clicked();
	}
}

void TPPPushButton::paintEvent(QPaintEvent *)
{
	QPainter painter(this);
	QPixmap pixmap;
	switch (status)
	{
	case NORMAL:
	{
		pixmap.load(pic_name);
		break;
	}
    case ENTER:
	{
		pixmap.load(pic_name + QString("_hover"));
		break;
	}
	case PRESS:
	{
		pixmap.load(pic_name + QString("_pressed"));
		break;
	}
    case NOSTATUS:
	{
        pixmap.load(pic_name + QString("_disable"));
		break;
	}
	default:
		pixmap.load(pic_name);
	}

	painter.drawPixmap(rect(), pixmap);
}

 

 

发布了25 篇原创文章 · 获赞 6 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 鲸 设计师: meimeiellie

分享到微信朋友圈

×

扫一扫,手机浏览