[英]Make a QMenu label bold without affecting its children
I'm trying to change the styling and/or font of the label/text on the QMenu, without affecting it's children. 我正在尝试更改QMenu上标签/文本的样式和/或字体,而不会影响它的子级。 I'm doing this in Python with PySide (which works just like Qt).
我正在使用PySide(与Qt一样)在Python中进行此操作。
I've tried: 我试过了:
menu = QtGui.QMenu()
f = menu.font()
f.setBold(True)
menu.setFont(f)
And 和
menu = QtGui.QMenu()
menu.setStyleSheet("QMenu{font-weight: bold;}")
Both of these would not change the label of the menu itself, yet will do it on all of its children. 这两个选项都不会更改菜单本身的标签,但会在所有子菜单上都执行此操作。
I would prefer to set the styling directly on the QMenu (or another class if it acts similarly and makes it possible) instead of applying a stylesheet on its parent. 我宁愿直接在QMenu上设置样式(或者如果它具有相似的行为并使之成为可能,则在另一个类上)而不是在其父级上应用样式表。
Goals 目标
The idea is that I have a menu with a variety of sub-menus (which are somewhat dynamic based on folders on a server) of which some need to be Bold and some Italic. 我的想法是,我有一个菜单,其中包含各种子菜单(根据服务器上的文件夹是动态的),其中一些需要粗体显示,而某些需要使用斜体显示。 Therefore I would like to add these sub QMenu's dynamically and style them accordingly.
因此,我想动态添加这些子QMenu并相应地设置其样式。
You can achieve it easy. 您可以轻松实现。 To understand the logic:
要了解逻辑:
QMenu
- is a widget which displays items QMenu
是一个显示项目的小部件 QMenu
to another QMenu
QMenu::menuAction
is placed in a base menu. QMenu
添加到另一个QMenu
QMenu::menuAction
将放置在基本菜单中。 menuAction
. menuAction
。 So to make you menu bold you just need to set a bold font to menuAction
of this menu. 因此,要使菜单变为粗体,只需要为该菜单的
menuAction
设置粗体即可。
Here is a simple working example: 这是一个简单的工作示例:
QMenu m; //base menu
QMenu sub; //sub menu
sub.setTitle("subMenu");
QAction* a1 = new QAction("act1", &m);
QAction* a2 = new QAction("act2", &m);
QAction* a3 = new QAction("act3", &m);
// set a bold font for a sub menu item
QFont f = sub.menuAction()->font();
f.setBold(true);
sub.menuAction()->setFont(f);
// add an action to the sub menu
sub.addAction(a3);
// add two actions and the sub menu to the base menu
m.addAction(a1);
m.addMenu(&sub);
m.addAction(a2);
// show the base menu
m.exec(QCursor::pos());
Read the Qt documentation about QSS selectors . 阅读有关QSS选择器的Qt文档。
For your case: you could not directly customize labels of specific menu items. 对于您的情况:您不能直接自定义特定菜单项的标签。 But you may insert
QWidgetAction
insead of QAction
and customize it as you want (place a label on QWidgetAction
and customize it). 但是,你可以插入
QWidgetAction
的欧洲工商管理学院QAction
和定制你想要的(放置在标签QWidgetAction
并进行自定义)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.