SetStyleSheet background-color doesn't work on a derived widget



  • If i set a background-color by setStyleSheet() on a QWidget directly that works perfect.
    But if i create an own widget, derived by QWidget, the background-color doesn't work in it.
    Does anybody have an idea why??? Many Thanks!!!

    Here the code which shows the difference:

    main.cpp:
    @#include <QtGui/QApplication>
    #include "mywidgets.h"

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    MainWidget w;
    w.show();

    return a.exec();
    }
    @

    mywidgets.h:
    @#include <QWidget>

    class MainWidget : public QWidget
    {
    Q_OBJECT

    public:
    explicit MainWidget(QWidget *parent = 0);
    };

    class RedWidget : public QWidget
    {
    Q_OBJECT

    public:
    explicit RedWidget(QWidget *parent = 0);
    };

    class YellowWidget : public QWidget
    {
    Q_OBJECT

    public:
    explicit YellowWidget(QWidget *parent = 0);
    };@

    mywidgets.cpp:
    @#include "mywidgets.h"
    #include <QHBoxLayout>
    #include <QWidget>

    RedWidget::RedWidget(QWidget *parent) :
    QWidget(parent)
    {
    this->setStyleSheet("background-color:red");
    }

    YellowWidget::YellowWidget(QWidget *parent) :
    QWidget(parent)
    {
    this->setStyleSheet("background-color:yellow");
    }

    MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent)
    {
    this->setMinimumWidth(800);
    this->setMinimumHeight(600);
    this->setStyleSheet("background-color:grey");

    QHBoxLayout* layout = new QHBoxLayout(this);

    /*
    // This works fine:
    QWidget* wYellow = new QWidget(this);
    QWidget* wRed = new QWidget(this);
    wYellow->setStyleSheet("background-color:yellow");
    wRed->setStyleSheet("background-color:red");
    */

    // But not this version:
    YellowWidget* wYellow = new YellowWidget(this);
    RedWidget* wRed = new RedWidget(this);

    layout->addWidget(wYellow);
    layout->addWidget(wRed);

    this->setLayout(layout);

    }
    @



  • Read the documentation for QWidget.

    http://doc.qt.nokia.com/4.7/stylesheet-reference.html



  • You mean


    If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:

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

    The above code is a no-operation if there is no stylesheet set.

    Warning: Make sure you define the Q_OBJECT macro for your custom widget.

    Yes, thanks - that works.
    But i wonder, to have to do such overhead. Why isn't it implemented in QWidget itself?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.