我正在尝试在 QMenu
中插入 QWidgetAction
,它将用作托盘的上下文菜单。当我这样做时,我的菜单中只会出现一个空行。
我正在使用:
- Qt 5.5.1。
- Plasma 5 桌面环境 (Linux)。
这是我的代码:
action = new QWidgetAction(0);
testw = new QWidget();
testl = new QLabel(QString("Test"), testw);
action->setDefaultWidget(testw);
menu.addAction(action);
trayIcon.setContextMenu(&menu);
如果我使用menu.addAction(QString("Test"))
;已正确显示。
所有变量都是我的类的成员。
最佳答案
只要您已经显示了菜单,那么问题就出在您包装 QLabel 的额外小部件上。这是 QWdigetAction 通常的工作方式:
QWidgetAction* pWidgetAction = new QWidgetAction(0); // no parent-owner?
QLabel* pLabelWidget = new QLabel("Test"); // label widget
pWidgetAction->setDefaultWidget(pLabelWidget); // label is a widget
menu.addAction(pWidgetAction); // add widget action
trayIcon.setContextMenu(&menu); // this I assume works
还不确定这些对象的生命周期(所有权)以及为什么 menu
和 trayIcon
不是指针,但您应该更清楚这一点。默认情况下,我总是使用 new
创建 UI 对象,并将父窗口小部件/对象地址传递给构造函数,尽管我们也可以将它们放在堆栈上(不灵活的方法)。
关于qt - QWidgetAction 不能在 QMenu 中作为托盘的上下文菜单工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34370904/