QSystemTrayIcon Not Showing Under Ubuntu

I wanted a simple system tray application that would work on both Windows and Linux. As C# doesn't really have a proper GUI for Linux (albeit you can come a long way using Windows Forms), I decided to go with QT.

Showing system tray was really easy:

Code
_tray = new QSystemTrayIcon(this);
connect(_tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(onTrayActivate(QSystemTrayIcon::ActivationReason)));

_tray->setIcon(trayIcon);
_tray->setToolTip(QCoreApplication::applicationName());
_tray->show();

Under Windows it worked beautifully. Under Ubuntu - not so. QT example for tray icon was pretty much equivalent and it worked flawlessly. But my simple example just wouldn't. It took me a while but I traced the issue.

Upon click I wanted to display a context menu. It seemed innocent enough to dynamically create it:

Code
void MainWindow::onTrayActivate(QSystemTrayIcon::ActivationReason reason) {
switch (reason) {
case QSystemTrayIcon::Context: {
QMenu menu(this);
menu.addAction("&Show", this, SLOT(onTrayShow()));
menu.addSeparator();
menu.addAction("E&xit", this, SLOT(onTrayExit()));

menu.exec(QCursor::pos());
} break;

case QSystemTrayIcon::DoubleClick: {
onTrayShow();
} break;

default: break;
}
}

And this works under Windows. But Ubuntu and it's Unity GUI don't really know what to do with tray icon without preassigned context menu. And thus tray icon is never actually displayed.

Once I figured that out, solution was simple. Just assign menu statically:

Code
_tray = new QSystemTrayIcon(this);
connect(_tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(onTrayActivate(QSystemTrayIcon::ActivationReason)));

QMenu* trayMenu = new QMenu(this);;
trayMenu->addAction("&Show", this, SLOT(onTrayShow()));
trayMenu->addSeparator();
trayMenu->addAction("E&xit", this, SLOT(onTrayExit()));
_tray->setContextMenu(trayMenu);

_tray->setIcon(trayIcon);
_tray->setToolTip(QCoreApplication::applicationName());
_tray->show();

Leave a Reply

Your email address will not be published. Required fields are marked *