Virgo is my name
Virgo is my name Home Blog About Login
Apply style sheet to custom QWidget classes after construction

Apply style sheet to custom QWidget classes after construction

Published by Virgo, on Jun 08, 2020. Unlicensed. 1147 views. Based on page loads (non unique).

I was doing a simple test with Qt's style sheet system. And found that for subclassed QWidgets applying style sheet after calling their constructors doen't take effect, not even with QStyle::polish().

Note: for custom widget classes that DO NOT inherit QWidget directly (e.g. classes that inheriting a QPushButton or a QCheckBox), styling with style sheet may just work perfectly. If you also used custom Qt property, you may need to do QStyle::polish() on the widgets everytime the property changes, for the widgets to properly repaint (calling QWidget::update() won't do a difference). Not so sure about the cause, not sure if this is even correct, I will update soon as I figure it out.

For those inherit QWidget directly, setting style sheet after construction doesn't take effect. And this time QStyle::polish() won't save it. I spent a whole lot of time Googling for possible explanations but didn't find any. When I was about to give up, I rechecked document for QStyle, and found this QStyle::drawPrimitive() thing.

The document doesn't come clear what it is for, but I decided to give it a try anyway, so I re-implemented QWidget::paintEvent():

void paintEvent(QPaintEvent *) override
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

And it works! (Though QStyle::polish() is still required for custom properties. )

Futher look into the document, there is also a QStylePainter, which can make the code one line lesser:

void paintEvent(QPaintEvent *) override
{
    QStyleOption opt;
    opt.initFrom(this);
    QStylePainter(this).drawPrimitive(QStyle::PE_Widget, opt);
}

Also, if you don't want to override QWidget::paintEvent(), there is another option. Instead of subclassing QWidget, do it with QWidget's already existed subclasses, like QFrame. Still, the document is not clear, of what is the actual matter here, guess it's the QStyleOption Subclasses. Refer to the document for details.

Virgo is my name
A website. ©2020 Virgo