Search code examples
c++qt4

QMenu: Set text color for specific QAction


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

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?


Solution

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

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