QMenu:为特定QAction设置文本颜色

时间:2022-04-14 08:44:58

I have a QMenu as context menu that looks like this:

我有一个QMenu作为上下文菜单,如下所示:

Menu
- information_A
- information_B
- information_C

Now i want the entry information_B to be painted in a different color. How can i archive this?

现在我想要以不同的颜色绘制条目信息_B。我该如何存档?

1 个解决方案

#1


1  

EDIT: I found the best solution in this post: link In your case it would be as simple as:

编辑:我在这篇文章中找到了最佳解决方案:链接在你的情况下,它将如下所示:

QMenu contextMenu(this);
QString menuStyle(
        "QMenu::item{"      
        "color: rgb(0, 0, 255);"
        "}"
    );
contextMenu.setStyleSheet(menuStyle);

For more options and possibilities take a look at the answer in the link I provided above.

有关更多选项和可能性,请查看我在上面提供的链接中的答案。

PREVIOUS SOLUTION:
You can use QWidgetAction instead of QAction, and define your QLabel with text and stylesheet you want, and then assign it to your QWidgetAction. But keep in mind that you have to tweak the width and height of your QLabel, in order for it to look the same as QAction does.

以前的解决方案:您可以使用QWidgetAction而不是QAction,并使用您想要的文本和样式表定义QLabel,然后将其分配给您的QWidgetAction。但请记住,您必须调整QLabel的宽度和高度,以使其看起来与QAction相同。

Sample code:

示例代码:

// label
QLabel *text = new QLabel(QString("your text here"), this);
text->setStyleSheet("color: blue"); 
// init widget action
QWidgetAction *widAct= new QWidgetAction(this);
widAct->setDefaultWidget(text);
contextMenu.addAction(widAct);

#1


1  

EDIT: I found the best solution in this post: link In your case it would be as simple as:

编辑:我在这篇文章中找到了最佳解决方案:链接在你的情况下,它将如下所示:

QMenu contextMenu(this);
QString menuStyle(
        "QMenu::item{"      
        "color: rgb(0, 0, 255);"
        "}"
    );
contextMenu.setStyleSheet(menuStyle);

For more options and possibilities take a look at the answer in the link I provided above.

有关更多选项和可能性,请查看我在上面提供的链接中的答案。

PREVIOUS SOLUTION:
You can use QWidgetAction instead of QAction, and define your QLabel with text and stylesheet you want, and then assign it to your QWidgetAction. But keep in mind that you have to tweak the width and height of your QLabel, in order for it to look the same as QAction does.

以前的解决方案:您可以使用QWidgetAction而不是QAction,并使用您想要的文本和样式表定义QLabel,然后将其分配给您的QWidgetAction。但请记住,您必须调整QLabel的宽度和高度,以使其看起来与QAction相同。

Sample code:

示例代码:

// label
QLabel *text = new QLabel(QString("your text here"), this);
text->setStyleSheet("color: blue"); 
// init widget action
QWidgetAction *widAct= new QWidgetAction(this);
widAct->setDefaultWidget(text);
contextMenu.addAction(widAct);