Search code examples
c++qtqt4qt5qwidget

Why does QWidget disappear after promoted?


I have a hierarchy of 3 widgets:

enter image description here

Each widget has the background color changed to a different color(using QSS) so that the output looks like:

enter image description here

All good here. But if I promote widget to a class derived from QWidget it disappears like so:

enter image description here

enter image description here

This is the code for my Custom widget:

custom.h:

#ifndef CUSTOM_H
#define CUSTOM_H

#include <QWidget>

class Custom : public QWidget
{
    Q_OBJECT
public:
    explicit Custom(QWidget *parent = 0);
};

#endif // CUSTOM_H

custom.cpp:

#include "custom.h"

Custom::Custom(QWidget *parent) :
    QWidget(parent)
{
}

Can anybody explain why are these weird things happening and what can I do to make the green widget show up??


Solution

  • A while ago I have already answered a similar question :)

    In order to qss stylesheets work for direct QWidget subclasses you should implement the paintEvent like this:

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