Reputation: 731
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 CustomLabel
QLabel
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.
Upvotes: 4
Views: 3273
Reputation: 623
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;
}
Upvotes: 0
Reputation: 2467
Try settings Qt::WA_StyledBackground
attribute for your custom label.
Upvotes: 1
Reputation: 11064
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 ();
}
Upvotes: 2
Reputation: 731
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;
}
Upvotes: 0