Apply different QSS stylesheet for custom QT class

旧时模样 提交于 2020-01-06 06:37:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!