QMainWindow->setStyleSheet behaves unexpected (Q_OBJECT causing problems?)

  • Using Qt 4.8.4 on Windows 7 (MSVC 2010) I have a standard QMainWindow in my app with toolbar and menu. I want to achieve that toolbar and menu keep their grey color, but the central widget should have a white background. My test case is an app with just one label in the central widget. In order to see the problem, add or remove the Q_OBJECT line in test.h

    When Q_OBJECT is there, only the label gets a white bg. If Q_OBJECT is commented out, the whole central widget is white. Of course, I want the whole area white, but also need Q_OBJECT.

    Here's the files:
    @#include "test.h"

    class testwin : public QMainWindow {
    QWidget *centralWidget;
    QToolBar *mainToolBar;

    testwin(QWidget *parent = 0) : QMainWindow(parent) {
        centralWidget = new test(this);
        mainToolBar = new QToolBar(this);
        this->addToolBar(Qt::TopToolBarArea, mainToolBar);
    ~testwin() {};


    int main(int argc, char *argv[])
    QApplication a(argc, argv);
    testwin w;
    w.centralWidget->setStyleSheet("background-color: white;");
    return a.exec();

    @#ifndef TEST_H
    #define TEST_H

    #include <QtGui>

    class test : public QWidget
    Q_OBJECT // remove this

    QLabel *label;

    test(QWidget *parent = 0&#41; {
        resize(400, 300);
        label = new QLabel(this);


    #endif // TEST_H

  • Lifetime Qt Champion


    Could you try with the latest Qt ? 4.8.5 in the 4 series, maybe even with Qt 5 to see if the behavior is the same.

  • This can be reproduced in Qt5.1

  • Hi,

    From the documentation of Qt stylesheet, we can find the answer of the problem:

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

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

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

  • Thanks a lot - this solves the issue. I hope I'm not the only one who considers this kind of unexpected (I mean, why doesn't QWidget's default implementation of paintEvent deal with this?).

    Anyway, all is well, another RTFM solved :)

Log in to reply

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