以QPushButton的initStyleOption为例
先看源码,该函数为保护函数
void QPushButton::initStyleOption(QStyleOptionButton *option) const
{
if (!option)
return;
Q_D(const QPushButton);
option->initFrom(this);
option->features = QStyleOptionButton::None;
if (d->flat)
option->features |= QStyleOptionButton::Flat;
#if QT_CONFIG(menu)
if (d->menu)
option->features |= QStyleOptionButton::HasMenu;
#endif
if (autoDefault())
option->features |= QStyleOptionButton::AutoDefaultButton;
if (d->defaultButton)
option->features |= QStyleOptionButton::DefaultButton;
if (d->down || d->menuOpen)
option->state |= QStyle::State_Sunken;
if (d->checked)
option->state |= QStyle::State_On;
if (!d->flat && !d->down)
option->state |= QStyle::State_Raised;
option->text = d->text;
option->icon = d->icon;
option->iconSize = iconSize();
}
重写该函数:
头文件
#ifndef XX_H
#define XX_H
#include <QtWidgets>
class PushButton : public QPushButton
{
public:
PushButton(QWidget *parent);
~PushButton();
void paintEvent(QPaintEvent *) override;
};
#endif // XX_H
源文件
#include "xx.h"
#include "private/qpushbutton_p.h"
PushButton::PushButton(QWidget *parent)
: QPushButton(parent)
{
}
PushButton::~PushButton()
{
}
void PushButton::paintEvent(QPaintEvent *)
{
QStylePainter p(this);
QStyleOptionButton option;
QPushButton::initStyleOption(&option);
p.drawControl(QStyle::CE_PushButton, option);
}
void QPushButton::initStyleOption(QStyleOptionButton *option) const
{
qInfo() << __LINE__;
if (!option)
return;
Q_D(const QPushButton);
option->initFrom(this);
option->features = QStyleOptionButton::None;
if (d->flat)
option->features |= QStyleOptionButton::Flat;
#if QT_CONFIG(menu)
if (d->menu)
option->features |= QStyleOptionButton::HasMenu;
#endif
if (autoDefault())
option->features |= QStyleOptionButton::AutoDefaultButton;
if (d->defaultButton)
option->features |= QStyleOptionButton::DefaultButton;
if (d->down || d->menuOpen)
option->state |= QStyle::State_Sunken;
if (d->checked)
option->state |= QStyle::State_On;
if (!d->flat && !d->down)
option->state |= QStyle::State_Raised;
option->text = d->text;
option->icon = d->icon;
option->iconSize = iconSize();
}