当前位置:网站首页>关于非虚函数的假派生

关于非虚函数的假派生

2022-07-06 03:21:00 氺月洞天

以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();
}

原网站

版权声明
本文为[氺月洞天]所创,转载请带上原文链接,感谢
https://blog.csdn.net/ch593030323/article/details/124941404