Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Stylesheet is not applied to custom QWidget

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.

like image 659
weblar83 Avatar asked Sep 12 '25 08:09

weblar83


2 Answers

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 ();
}
like image 121
m7913d Avatar answered Sep 13 '25 22:09

m7913d


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

like image 34
mentalmushroom Avatar answered Sep 13 '25 21:09

mentalmushroom