Set background color QMenu's items
-
Hi,
I would like to change color to red in QMenu item.
QMenu contextMenu(tr("Context menu"), this); QAction action1("Remove Data Point", this);
I can do this like that:
contextMenu.setStyleSheet("QMenu::item:selected {background:red;}");
But when I do that, item's text color is changed and item's text will start more on the left side ( look at the picture - here I changed in setStyleSheet text background to rgb(0,0,0) ). How can I don't changed other things that background color ( no text color, no font, no align )?
-
Hi
Well you have to use margin and other keys to align all texts the same way
https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenuThere is no way to avoid it shifting the text.
But you can fully style it so it looks good even it will then no longer 100% look like a
standard menu.I think stylesheet is the most easy way to get red background.
I tried qwidgetaction but it had other issues.update:
Maybe something like
QMenu { background-color: white; } QMenu::item { padding: 2px 20px 2px 20px; border: 1px solid transparent; spacing: 20px; } QMenu::item:selected { border-color: darkblue; background: rgb(255, 0, 0); color:white; } QMenu::separator { height: 2px; margin: 2px 5px 2px 4px; } QMenu::indicator { width: 20px; height: 13px; }
-
Hi
When you put a stylesheet on widgets.
Its all or nothing as then its not the normal the drawing anymore.
That means you must also use other keys in the stylesheet to get QMenu to look how you want. -
Hi
Sadly there is no delegate for it. That would have been cool.
There is
https://doc.qt.io/qt-5/qwidgetaction.html
But that is for using a custom widget.
We could use
style()->drawControl(QStyle::CE_MenuItem, &opt, &p, this);
to draw the actual menu in a custom widget but Im not sure its the best way as
we still might not have all other elements covered.Just so I know. The goal is to have a red background?
That is it? -
Hi
Well you have to use margin and other keys to align all texts the same way
https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenuThere is no way to avoid it shifting the text.
But you can fully style it so it looks good even it will then no longer 100% look like a
standard menu.I think stylesheet is the most easy way to get red background.
I tried qwidgetaction but it had other issues.update:
Maybe something like
QMenu { background-color: white; } QMenu::item { padding: 2px 20px 2px 20px; border: 1px solid transparent; spacing: 20px; } QMenu::item:selected { border-color: darkblue; background: rgb(255, 0, 0); color:white; } QMenu::separator { height: 2px; margin: 2px 5px 2px 4px; } QMenu::indicator { width: 20px; height: 13px; }