简体   繁体   中英

System tray application Linux Qt/C++

I'm writing an application in C++ with Qt that utilizes the system tray. I have implemented the system tray using a QSystemTrayIcon class as shown in the examples, but it doesn't have the same behavior as other system tray icons that are present on my computer. For instance, I have Spotify installed on Ubuntu 12.04 and it shows a system tray icon with a drop down menu. With my application, it shows a system tray icon with a context menu, meaning you have to right click it to make the menu active. With Spotify, all that needs to be done is to click on the icon and the menu will show. What can I do to get native system tray icons in Ubuntu? I'm fine with using specific code for X11/Linux and not the built-in Qt functions. Thanks much.

Here's my code:

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (trayIcon->isVisible()) {
        hide();
        event->ignore();
    }
}

void MainWindow::createActions()
{
    restoreAction = new QAction(tr("&Show"), this);
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(show()));

    quitAction = new QAction(tr("&Exit"), this);
    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}

void MainWindow::createTrayIcon()
{
    trayIconMenu = new QMenu(this);
    accountsMenu = trayIconMenu->addMenu(tr("Accounts"));
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(restoreAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);

    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setContextMenu(trayIconMenu);
}

Try to drop down menu from activated signal of QSystemTrayIcon.

void Window::iconActivated(QSystemTrayIcon::ActivationReason reason)
 {
     switch (reason) {
         case QSystemTrayIcon::Trigger:
             // show your menu here
     }
 }

I am commenting for the benefit of others here... I had the same issue when we deployed our product (built using Qt)on Ubuntu 12.04 LTS. We use the qt.conf way of deployment. After a lot of hunting and going through the source on sni-qt I found that plugins need to be properly found out. So I created and copied the plugins from our build environment to the plugins directory relative to my application path mentioned in qt.conf against the 'Plugins = ' entry. Also made sure that sni-qt is update and installed on the deployed Ubuntu 12.04 machine. The menus appeared as they appear for other tray applications. You can copy plugins from /usr/lib/i386-linux-gnu/qt4/plugins/ on a 32 bit machine or its equivalent path on 64 bit machine. For this problem plugin under systemtrayicon is the required one.

HTH.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM