Question

I want to set color of the border of a menu item when user set focus on it. First - item::selected, is this right property? And if yes, how to set this? Do i use Designer or do it manually in C++ code?

Customizing QMenu Individual items of a QMenu are styled using the 'item' subcontrol as follows:  

         QMenu {
             background-color: #ABABAB; /* sets background of the menu */
             border: 1px solid black;  }

         QMenu::item {
             /* sets background of menu item. set this to something non-transparent
                 if you want menu color and menu item color to be different */
             background-color: transparent;  }

         QMenu::item:selected { /* when user selects item using mouse or keyboard */
             background-color: #654321;  }

OK, but where to put this in Qt 5.0? Do I use this in Designer in stylesheet property? I guess NO. In my .cpp files? I can do setStyleSheet on my menu but how to specify ::item::selected?

#include "MainWindow.h"
#include <QtWidgets/QWidget>
#include <QtWidgets/QMessageBox>
cf16tradingclient_1::cf16tradingclient_1(){
    widget.setupUi(this);
    widget.menuMarket->setStyleSheet(?????????) // I want item::selected
}
Was it helpful?

Solution

You simply do:

widget.menuMarket->setStyleSheet("QMenu::item:selected{border:1px solid red;}");

That's the right place to do it if you only want one specific menu to behave like that. (I don't see why setting that in Designer wouldn't work. Give it a try. But I'm not familiar with it myself.)

If you want all your menus to have the same style, do it at the QApplication level, in your main or some other piece of code that runs once at startup.

QApplication app(argc, argv);
// ...
app.setStyleSheet("QMenu::item:selected {border: 5px solid yellow;}");
// ...

And you can combine the two. The stylesheet you place on a specific widget (first example) will override the global stylesheet (much like CSS does).

This works the same in Qt4 and Qt5, though Qt5 might have more style options.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top