Please nominate your Qt Champions for 2021!

[SOLVED]please help me understand stylesheet

  • Hi
    I am having trouble with stylesheets

    I have a main window and have added a TestWidget that is derived from QWidget.
    I now try to set the background in the constructor for TestWidget-
    setStyleSheet("background-color: red");
    When the application is run the background color is not set.
    I tried this with in QDesigner, the background color is displayed in QDesigner but again when the application is run the background color is not set.

    If I use a QWidget then the background is as expected.

    What am I doing wrong



  • Hi, the answer can be found in the documentation:

    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);

    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.

  • Thanks!!

  • I recommend you use QTCreator to manage stylesheet.

    If you select your object in QtCreator ui designer page, you can edit the field "stylesheet", the code will be generated automatically.
    You can right click on your derived QWidget and select "promote to" then write the header class of your new widget. That way, you can use designer to manipulate the element

    #NameOfWidgetHere {
    background-color: red;


    QWidget#NameOfWidgetHere {
    background-color: red;

Log in to reply