最近想做一个自定义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);
}
正常,按下
下一章,我们继续修改,使其具有集体互斥性。