Can't add menu to QSystemTrayIcon
-
Hi, I can't seem to add a menu to QSystemTrayIcon.
I've followed this tutorial, which showed me how to get the icon to the system tray, but now I can't add a context menu.
Here's what I have:tray = new QSystemTrayIcon(this); //tray declared in .h file as a class tray->setVisible(true); tray->setIcon(QIcon(":/icons/clock.png")); tray->showMessage("Screen on time", "Screen on time service enabled"); QMenu trayMenu; trayMenu.addSection("menu"); tray->setContextMenu(trayMenu); -
Hi, I can't seem to add a menu to QSystemTrayIcon.
I've followed this tutorial, which showed me how to get the icon to the system tray, but now I can't add a context menu.
Here's what I have:tray = new QSystemTrayIcon(this); //tray declared in .h file as a class tray->setVisible(true); tray->setIcon(QIcon(":/icons/clock.png")); tray->showMessage("Screen on time", "Screen on time service enabled"); QMenu trayMenu; trayMenu.addSection("menu"); tray->setContextMenu(trayMenu);@Sucharek said in Can't add menu to QSystemTrayIcon:
QMenu trayMenu;Not my area, and I have no idea whether the whole concept works/is supposed to work. But if this your actual code (which who knows, since it's
QSystemTrayIcon::setContextMenu(QMenu *menu)and you are passing aQMenunot aQMenu *so it should not compile), theQMenu trayMenuwill go out of scope and be destroyed? -
@Sucharek said in Can't add menu to QSystemTrayIcon:
QMenu trayMenu;Not my area, and I have no idea whether the whole concept works/is supposed to work. But if this your actual code (which who knows, since it's
QSystemTrayIcon::setContextMenu(QMenu *menu)and you are passing aQMenunot aQMenu *so it should not compile), theQMenu trayMenuwill go out of scope and be destroyed? -
@Sucharek
Of course it will! Why should passing it anullptrfor itsQMenube acceptable?
C/C++ basics: consider what you need to do about the scope/lifetime of theQMenuyou pass to it. -
Oh, yeah, got it now, thanks.
Just need to give QMenu proper configuration now, because it just 2 pixels lol.@Sucharek
I imagine you made theQMenu trayMenuorQMenu *trayMenu = new QMenua member variable of some class, which persists for its desired lifetime. Note that in Qt you often have to consider this lifetime declaration for various things which need to persist; we see lots of posts where user has only created object as a method local variable and does not realise it gets destroyed on scope closure, so you are not the first to have come a cropper on this! :) -
@Sucharek
I imagine you made theQMenu trayMenuorQMenu *trayMenu = new QMenua member variable of some class, which persists for its desired lifetime. Note that in Qt you often have to consider this lifetime declaration for various things which need to persist; we see lots of posts where user has only created object as a method local variable and does not realise it gets destroyed on scope closure, so you are not the first to have come a cropper on this! :)