4

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?

Zaiborg
  • 2,492
  • 19
  • 28
  • It is always hard to say that something is not possible, but... I'd say impossible. At least in an easy way. I might overlook somethig, but I am afraid, you have to subclass QMenu and do the drawing yourself, i.e. overloading QPaintEvent. – Greenflow May 01 '15 at 07:28
  • ive checked the source of `QMenu`s paint event and it calls all sorts of hidden members. so i guess when using the `LGPL` there is no way to use existing functionality? – Zaiborg May 02 '15 at 10:40
  • I don't know. I checked the available api and did not find something, which could solve your problem easily. As I said, you probably have to subclass QMenu yourself and overload QPaintEvent. This has nothing to do with LGPL. I just don't think this easy looking QMenu might be surprisingly difficult to be drawn. I suppose... <-- you see much speculaton ...you have to find the proper rectangle for you menu item and draw it with help of the active style yourself. Nowadays I would not bother with something like that (if the choice is mine), but use qml. – Greenflow May 02 '15 at 10:53

2 Answers2

5

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);
Community
  • 1
  • 1
Ion Ureche
  • 74
  • 1
  • 5
1

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.

Ilya
  • 139
  • 1
  • 3