Hello! Faced such a difficulty:

I wrote my widget, redefined the paintEvent () method in it:

class My_PushButton : public QPushButton { //какой то код }; 

I want to apply the styles specified in the style.qss file to this widget.

And in any way it does not work. Styles are not applied to the widget, only to their own, they are applied to all the rest.

through setObjectName I set the name, and in the styles I tried to prescribe in different ways:

 #mybutton My_PushButton#mybutton QPushButton#mybutton QPushButton>My_PushButton#mybutton QPushButton My_PushButton#mybutton 

None of the above options worked. Tell me how to set selectors correctly, to your own widgets

  • one
    >> redefined the paintEvent () method in it: << Do you call the parent QPushButton :: paintEvent method inside your own? - test123
  • I do not call the method myself. I use the Q_UNUSED (event) macro - Sergey Zinovev
  • The first line of your overridden method should be the line calling the parent QPushButton :: paintEvent (event); - test123
  • You need to watch the source of QPushButton, you may be able to find out from there how he applies styles - test123
  • one
    test123, calling the parent class method solved the problem! Thank you - Sergey Zinovev

1 answer 1

Free translation of official documentation :

Qt Style Sheets style sheets use the QObject::className() method to determine the type of the selector. For a widget inside a namespace, this method returns the value <namespace>::<classname> , which conflicts with the accepted Sub-Controls syntax. To solve this problem, you need to replace :: with -- .

Example:

 namespace ns { class MyButton : public QPushButton { Q_OBJECT public: explicit MyButton(QWidget* parent = nullptr) : QPushButton(parent) { qDebug() << tr("constructor ns::MyButton() done."); } }; const QString mybuttonStyle() { return QString("ns--MyButton { background-color: yellow; color: red }"); } } int main(int argc, char* argv[]) { QApplication a(argc, argv); ns::MyButton b; QObject::connect(&b, &ns::MyButton::clicked, &a, &QApplication::quit); b.setText(a.tr("MyButton")); b.setStyleSheet(ns::mybuttonStyle()); b.show(); return a.exec(); } 

The style string for the same element defined without using the namespace will look like this:

 "MyButton { background-color: yellow; color: red }"