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:

1
QSystemTrayIcon *m_sysTrayIcon; // system tray

Then implement in .cpp:

1
2
3
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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:

1
QMenu *m_menu; // menu

Then in .cpp:

1
2
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:

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

Then before setting the menu on the icon, add:

1
2
3
4
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:

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

Implement them:

1
2
3
4
5
6
7
8
9
10
// tray show main window
void MainWindow::on_showMainAction()
{
this->show();
}
// tray exit
void MainWindow::on_exitAppAction()
{
qApp->exit();
}

Finally, connect signals and slots:

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

Add a System Tray to a Qt Application
https://greatzaochen.dev/en/posts/dce12727/
Author
Zao_chen
Posted on
November 19, 2024
Licensed under