// LATEST

Add a System Tray to a Qt Application

A quick intro on how to add a system tray to a Qt application

Brief intro

image20241119194056367

Start building

Add the tray icon

Use QSystemTrayIcon. First create one in .h under private:

QSystemTrayIcon *m_sysTrayIcon; // system tray

Then implement in .cpp:

m_sysTrayIcon = new QSystemTrayIcon(this); // create QSystemTrayIcon
QIcon icon = QIcon(":/img/img/logo.png"); // icon from resources
m_sysTrayIcon->setIcon(icon);

Check the icon setup. If it fails, there will be no error but the tray will not show.

Next, add events for the tray icon:

connect(m_sysTrayIcon, &QSystemTrayIcon::activated, // connect slot
        [=](QSystemTrayIcon::ActivationReason reason)
        {
            switch(reason)
            {
            case QSystemTrayIcon::Trigger: // single click
                // click event
                break;
            case QSystemTrayIcon::DoubleClick: // double click
                // double-click event
                break;
            default:
                break;
            }
        });

Add the tray menu

This is the menu shown when you right-click the tray icon. Use QMenu. Create in .h:

QMenu *m_menu; // menu

Then in .cpp:

m_menu = new QMenu(this);
m_sysTrayIcon->setContextMenu(m_menu); // assign QMenu to QSystemTrayIcon

Add menu items

A menu needs actions. Use QAction to add actions. Here is an example with "Show Main Window" and "Exit":

Add in .h:

QAction *m_showMainAction; // show main window
QAction *m_exitAppAction; // exit app

Then before setting the menu on the icon, add:

m_showMainAction = new QAction("Main Window", this);
m_exitAppAction = new QAction("Exit", this);
m_menu->addAction(m_showMainAction); // add menu item: show main window
m_menu->addAction(m_exitAppAction); // add menu item: exit app

You also need to add actions for these buttons.

Add in private slots:

void on_showMainAction(); // open main window
void on_exitAppAction(); // exit app

Implement them:

// tray show main window
void MainWindow::on_showMainAction()
{
    this->show();
}
// tray exit
void MainWindow::on_exitAppAction()
{
    qApp->exit();
}

Finally, connect signals and slots:

connect(m_showMainAction,SIGNAL(triggered()),this,SLOT(on_showMainAction()));
connect(m_exitAppAction,SIGNAL(triggered()),this,SLOT(on_exitAppAction()));

No comments yet

Share your thoughts and keep the conversation clear and kind.