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?
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.

// 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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With