如何在Qt中设置菜单::项目::选定的样式

how to set style of menu::item::selected in Qt?

本文关键字:项目 样式 菜单 Qt 设置      更新时间:2023-10-16

我想设置当用户设置焦点时菜单项边框的颜色。第一项:选中,这是正确的属性吗?如果是,如何设置?我使用设计器还是在c++代码中手动完成?

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

好的,但是在哪里把它放在Qt 5.0?在样式表属性中使用Designer吗?我想没有。在我的。cpp文件中?我可以在我的菜单上做setStyleSheet,但如何指定::item::选定?

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

你只需:

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

如果您只希望一个特定的菜单像那样工作,那么这是正确的位置。(我不明白为什么在Designer中设置它不起作用。试试吧。但我自己也不熟悉。

如果你想让你所有的菜单都有相同的风格,在QApplication级别,在你的main或其他一些在启动时运行一次的代码中做。

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

你可以把两者结合起来。放置在特定小部件上的样式表(第一个示例)将覆盖全局样式表(很像CSS)。

这在Qt4和Qt5中工作相同,尽管Qt5可能有更多的样式选项