问题
I am using a qss stylesheet for my gui. It works well but I would like to define a different style sheet for my custom widget.
By example, QPushbutton
's style works well but I would like to apply a different style for MyQPushButton
(extends from QPushButton).
I tried something like this :
MyQPushButton
{
color: #dcdcdc;
// some code here
}
QPushButton
{
color: #b1b1b1;
// some code here
}
But QPushButton
's style has been applied on MyQPushButton
.
How to override this behavior ?
回答1:
If you want to style a specific element in your project, you can use it like that;
QPushButton#MyQPushButton
{
color: #dcdcdc;
// some code here
}
I assume that, you've already named your new QPushButton
object as MyQPushButton
, you can name an element like this;
QPushButton* myButton = new QPushButton;
myButton->setObjectName("MyQPushButton");
Without naming your element, you can't access it to give it a overrided style.
回答2:
Ozan Yurtsever's answers works but is bad practice.
You should not use object names for stylesheet, except if you want to style a very unique widget in your application. It is prone to error and more verbose.
Qt stylesheets already allows what you want by default, you can overwrite the style for subclasses (see the end of this part of the doc).
As said in the doc, the order of declarations in the stylesheet matters, so your stylesheet should be :
QPushButton
{
color: #b1b1b1;
// some code here
}
MyQPushButton
{
color: #dcdcdc;
// some code here
}
Otherwise the style of QPushButton
will override the style of MyQPushButton
because MyQPushButton
is also a QPushButton
.
It is also possible to limit the scope of your style to the class only and not the subclasses with .QPushButton { /*some code*/ }
, see the doc about selectors.
One last tip, I had issues with stylesheet not working for subclass, check if you did not forget the Q_OBJECT
macro in the subclass.
来源:https://stackoverflow.com/questions/53706489/apply-different-qss-stylesheet-for-custom-qt-class