Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QMenu: Set text color for specific QAction

Tags:

c++

qt4

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?

like image 665
Zaiborg Avatar asked Oct 26 '25 21:10

Zaiborg


2 Answers

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);
like image 76
Ion Ureche Avatar answered Oct 29 '25 11:10

Ion Ureche


If you are only looking to style a single item in the menu, you can set it as default with QMenu::setDefaultAction and style a default menu item with the QMenu::item:default selector.

I.e.:

QMenu* menu = new QMenu("My menu");
QAction* actionToStyle = new QAction("My action");
menu->addAction(actionToStyle);
menu->setDefaultAction(actionToStyle);
menu->setStyleSheet("QMenu::item:default { color: #ff0000; }");

The limitation of this method is that it can apply special styling to only one item.

like image 21
Ilya Avatar answered Oct 29 '25 12:10

Ilya