I'm creating my custom push button class by subclassing QPushButton
. However for some reason setting that class's CSS in its constructor has no effect; I have to do it in for example paintEvent
, then everything is fine. I could just have a global .qss
file and set it for the entire application, but I want the class to manage its own styles. Why doesn't my approach work?
The code:
custompushbutton.h
class CustomPushButton: public QPushButton
{
Q_OBJECT
public:
explicit CustomPushButton(QWidget *parent = 0);
~CustomPushButton() = default;
};
custompushbutton.cpp
CustomPushButton::CustomPushButton(QWidget *parent)
: QPushButton(parent)
{
setStyleSheet("background-color: black;"); // this does not work
}
EDIT: For future readers, if you're having a similar issue (i.e. Qt seems to ignore your CSS you set in code), see if you haven't edited the object's styleSheet
property in Qt Creator - scroll down in the properties list and make sure styleSheet
is empty and NOT BOLD - that was the issue in my case. If it is bold, it means Qt is still using that empty field as the object's CSS, thereby overriding your styles. To clear it either hit the little arrow next to the field in Qt Creator or open up the .ui file and delete the <styleSheet>
XML property.
Thanks to JMik for pointing me in the right direction.
The performance cost of setting a stylesheet is surprisingly high, especially if you're developing for an embedded system.
I'd suggest, like you said, using a global stylesheet and specify the class name, like this:
this way all
CustomPushButton
will have the same style, and the object will take less time to create.As for the reason why it doesn't work in your case, I'd guess maybe your accidentally changing the stylesheet again after the creation of the CustomPushButton.
I tested your code on my side and it worked, so it probably has something to do with code your not showing