CSS Stylesheet is not applied to custom QWidget

2.8k Views Asked by At

What I'm trying to do is to apply custom CSS to a custom widget deriving from QLabel but I'm having no luck.

I have the custom class defined as:

class CustomLabel : public QLabel {

}

I've not re-implemented the paintEvent function as I thought that given that the standard QLabel supports CSS stylesheets, I would just need to refer to this new widget in CSS, for example:

CustomLabel {
    background-color: #111111;
    font-size: 18px;
    font-weight: bold;
}

Unfortunately at run-time, no style is applied the CustomLabel and the default QLabel style is applied.

Can anyone suggest why my CSS rules are being ignored for CustomLabel?

Steps to Recreate

  1. Create a Qt Widgets project using Qt Creator
  2. Add a custom class derived from QLabel and call it CustomLabel
  3. Add a QLabel onto a form using the designer
  4. Promote the label to a CustomLabel class
  5. Apply the stylesheet using the following code in main.cpp:

    a.setStyleSheet("CustomLabel {font-weight: bold;}");
    
  6. Run the program and notice how CustomLabel is not styled in accordance with the CSS style.

4

There are 4 best solutions below

4
On

You should use the macro Q_OBJECT inside your CustomLabel definition, otherwise CustomLabel is not known to Qt's type system:

class CustomLabel : public QLabel {
    Q_OBJECT
}

MCVE

CustomLabel.h:

#include "QLabel"
class CustomLabel : public QLabel {
  Q_OBJECT
};

main.cpp:

#include "QApplication"
#include "CustomLabel.h"
int main(int argc, char * argv[])
{
  QApplication a(argc, argv);
  a.setStyleSheet("CustomLabel {font-weight: bold; background-color: red;}");

  CustomLabel label;
  label.setText ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua");
  label.show ();

  a.exec ();
}
2
On

Ok, so I've managed to find a "workaround" rather than a proper answer: use the accessibleName parameter.

So in Qt Creator, assign a value such as CustomLabel to the accessibleName field of the QLabel and in the CSS file, add the following:

QLabel[accessibleName="CustomLabel"] {
    font-size: 11px;
}
0
On

As pat mentioned above in a short comment, you have to look out for your namespaces too, and mark them in the CSS file. In your case the CSS snippet should look like follows if the class is embedded in the UI namespace:

UI--CustomLabel {
    background-color: #111111;
    font-size: 18px;
    font-weight: bold;
}
0
On

Try settings Qt::WA_StyledBackground attribute for your custom label.