Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change QAction background color using stylesheets (css)?

Tags:

css

qt

pyqt

I have some QActions in my QToolBar. QAction doesn't have any stylesheets, so I am trying to use QToolBar stylesheet to change QAction background color. It works for every QActions in QToolBar

QToolButton{ background: red; }

But I need to change some QAction background to red and some to green.

I've tried this to change only one QAction

QToolButton:nth-of-type(3){ background: red; }

but it doesn't work.

Any idea how to change backgroun only for some QActions?

like image 295
Meloun Avatar asked Nov 20 '25 05:11

Meloun


1 Answers

You can use id selectors in CSS, they will select on object names. For this to work, you need to transfer action object names to the widgets used in the toolbar. To keep it easy to refer to actions and widgets by name, the actions should be given a name, too.

enter image description here

// https://github.com/KubaO/stackoverflown/tree/master/questions/action-style-32460193
#include <QtWidgets>

void nameAction(QToolBar * bar, QAction * action, const char * name = nullptr) {
   if (name && action->objectName().isEmpty())
      action->setObjectName(name);
   bar->widgetForAction(action)->setObjectName(action->objectName());
}

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QToolBar tb;
   nameAction(&tb, tb.addAction("Foo"), "foo");
   nameAction(&tb, tb.addAction("Bar"), "bar");
   nameAction(&tb, tb.addAction("Baz"), "baz");
   tb.setStyleSheet(
            "QToolButton#foo { background:red }"
            "QToolButton#baz { background:blue }");
   tb.show();
   return app.exec();
}
like image 111
Kuba hasn't forgotten Monica Avatar answered Nov 22 '25 03:11

Kuba hasn't forgotten Monica