2

I'm trying to insert a QWidgetAction inside a QMenu, which will be used as a context menu for tray. When I do this, I only get an empty line inside my menu.

I'm using:

  • Qt 5.5.1.
  • Plasma 5 desktop environment (Linux).

Here is my code:

action = new QWidgetAction(0);
testw = new QWidget();
testl = new QLabel(QString("Test"), testw);

action->setDefaultWidget(testw);

menu.addAction(action);
trayIcon.setContextMenu(&menu);

If I use menu.addAction(QString("Test")); it is displayed properly.

All the variables are members of my class.

mvlabat
  • 577
  • 4
  • 17
  • 1
    I don't think that can possibly work. Menus of system tray icons are not managed by the application; the "description" of the menu is serialized through DBus. Hence you can't embed widgets in there. – peppe Dec 19 '15 at 14:21
  • I've tried the solution by @AlexanderVX and similar approaches but (like @peppe says) this doesn't work for me in the system tray (i'm running Lubuntu 14.04). However the workaround that i'm using -- since in my case i only need to display text -- is to call the `setDisabled` method for the `QAction` that i want to use as a label – sunyata Jun 15 '17 at 14:50

1 Answers1

3

As long as you already have the menu shown then the problem is with extra widget you wrap the QLabel with. This is the way QWdigetAction usually works:

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

Also unsure of the life-cycle of these objects (the ownership) and why menu and trayIcon are not pointers but you should be more clear about that. By default I always create UI objects with new and pass the parent widget/object address to constructor though we can have those on stack as well (not flexible approach).

Alexander V
  • 8,351
  • 4
  • 38
  • 47