QPushButton源码及自定义按钮

最近想做一个自定义QPushButton使其具有,normal,hover,pressed三种状态,并且具有互斥性,发现QPushButton不能实现自己的想法(不想用QRadioButton),毕竟QPushButton和QRadioButton还是不同的,比如QPushButton可以按下,然后再单击一次,按钮又弹起。而一组按钮又可以互斥。这是QRadioButton是不能实现的,所以就拔了一下Qt的源码。先看位置:

qtbase:

widgets:

 

可以看到 qabstractbutton和qpushbutton都在这里面。

接下来分析其中的代码:

先做一个简单的修改(本类继承自QPushButton):

#include "QPushButtonEx.h"
#include <QStylePainter>
#include <QStyleOptionButton>
#include <qpixmap.h>
QPushButtonEx::QPushButtonEx(QWidget *parent)
	: QPushButton(parent)
{
}

QPushButtonEx::QPushButtonEx(const QString &text, QWidget *parent)
	:QPushButton(text,parent)
{

}
QPushButtonEx::QPushButtonEx(const QIcon& icon, const QString &text, QWidget *parent)
	:QPushButton(icon, text, parent)
{

}

QPushButtonEx::~QPushButtonEx()
{
}

 
void QPushButtonEx::paintEvent(QPaintEvent *)
{
	QStylePainter p(this);
	QStyleOptionButton option;
	initStyleOption(&option);
	if (isChecked())
	{
		QPixmap pixmap(":/testCustomPushButton/ArrowPressed.png");
		QSize size = this->size();
		pixmap.scaled(size, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
		QSize pixmapSize = pixmap.size();
		p.drawPixmap(0, 0, size.rwidth(), size.rheight(), pixmap);
		
	}
		
	else
	{
		QPixmap pixmap(":/testCustomPushButton/ArrowNormal.png");
		QSize size = this->size();
		pixmap.scaled(size, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
		QSize pixmapSize = pixmap.size();
		p.drawPixmap(0, 0, size.rwidth(), size.rheight(), pixmap);
	}
		

//	QPushButton::paintEvent(p);
}
 

 正常,按下

 下一章,我们继续修改,使其具有集体互斥性。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值