如何使用样式表(css)更改QAction背景颜色?

时间:2015-09-08 14:18:07

标签: css qt pyqt

我的QToolBar中有一些QActions。 QAction没有任何样式表,因此我尝试使用QToolBar样式表来更改QAction背景颜色。它适用于QToolBar中的每个QAction

QToolButton{ background: red; }

但是我需要将一些QAction背景改为红色,一些改为绿色。

我试过这只改变一个QAction

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

但它没有用。

知道如何仅针对某些QA更改背景吗?

1 个答案:

答案 0 :(得分:2)

您可以在CSS中使用id选择器,他们将选择对象名称。为此,您需要将操作对象名称传输到工具栏中使用的窗口小部件。为了便于按名称引用操作和小部件,应该为操作命名。

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();
}