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
QLabel and call it CustomLabelQLabel onto a form using the designerCustomLabel classApply the stylesheet using the following code in main.cpp:
a.setStyleSheet("CustomLabel {font-weight: bold;}");
Run the program and notice how CustomLabel is not styled in accordance with the CSS style.
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 ();
}
Try settings Qt::WA_StyledBackground attribute for your custom label.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With