System Tray Icon Example¶
The System Tray Icon example shows how to add an icon with a menu and popup messages to a desktop environment’s system tray.
Modern operating systems usually provide a special area on the desktop, called the system tray or notification area, where long-running applications can display icons and short messages.
This example consists of one single class, Window
, providing the main application window (i.e., an editor for the system tray icon) and the associated icon.
The editor allows the user to choose the preferred icon as well as set the balloon message’s type and duration. The user can also edit the message’s title and body. Finally, the editor provides a checkbox controlling whether the icon is actually shown in the system tray, or not.
Window Class Definition¶
The Window
class inherits QWidget
:
class Window(QDialog): Q_OBJECT # public Window() def setVisible(visible): protected: def closeEvent(event): slots: = private() def setIcon(index): def iconActivated(reason): def showMessage(): def messageClicked(): # private def createIconGroupBox(): def createMessageGroupBox(): def createActions(): def createTrayIcon(): iconGroupBox = QGroupBox() iconLabel = QLabel() iconComboBox = QComboBox() showIconCheckBox = QCheckBox() messageGroupBox = QGroupBox() typeLabel = QLabel() durationLabel = QLabel() durationWarningLabel = QLabel() titleLabel = QLabel() bodyLabel = QLabel() typeComboBox = QComboBox() durationSpinBox = QSpinBox() titleEdit = QLineEdit() bodyEdit = QTextEdit() showMessageButton = QPushButton() minimizeAction = QAction() maximizeAction = QAction() restoreAction = QAction() quitAction = QAction() trayIcon = QSystemTrayIcon() trayIconMenu = QMenu()
We implement several private slots to respond to user interaction. The other private functions are only convenience functions provided to simplify the constructor.
The tray icon is an instance of the QSystemTrayIcon
class. To check whether a system tray is present on the user’s desktop, call the static isSystemTrayAvailable()
function. Associated with the icon, we provide a menu containing the typical minimize, maximize, restore and quit actions. We reimplement the setVisible()
function to update the tray icon’s menu whenever the editor’s appearance changes, e.g., when maximizing or minimizing the main application window.
Finally, we reimplement QWidget
‘s closeEvent()
function to be able to inform the user (when closing the editor window) that the program will keep running in the system tray until the user chooses the Quit entry in the icon’s context menu.
Window Class Implementation¶
When constructing the editor widget, we first create the various editor elements before we create the actual system tray icon:
def __init__(self): createIconGroupBox() createMessageGroupBox() iconLabel.setMinimumWidth(durationLabel.sizeHint().width()) createActions() createTrayIcon() connect(showMessageButton, QAbstractButton.clicked, self, Window.showMessage) connect(showIconCheckBox, QAbstractButton.toggled, trayIcon, QSystemTrayIcon.setVisible) connect(iconComboBox, QComboBox.currentIndexChanged, self, Window::setIcon) connect(trayIcon, QSystemTrayIcon.messageClicked, self, Window.messageClicked) connect(trayIcon, QSystemTrayIcon.activated, self, Window.iconActivated) mainLayout = QVBoxLayout() mainLayout.addWidget(iconGroupBox) mainLayout.addWidget(messageGroupBox) setLayout(mainLayout) iconComboBox.setCurrentIndex(1) trayIcon.show() setWindowTitle(tr("Systray")) resize(400, 300)
We ensure that the application responds to user input by connecting most of the editor’s input widgets (including the system tray icon) to the application’s private slots. But note the visibility checkbox; its toggled()
signal is connected to the icon's setVisible()
function instead.
def setIcon(self, index): icon = iconComboBox.itemIcon(index) trayIcon.setIcon(icon) setWindowIcon(icon) trayIcon.setToolTip(iconComboBox.itemText(index))
The setIcon()
slot is triggered whenever the current index in the icon combobox changes, i.e., whenever the user chooses another icon in the editor. Note that it is also called when the user activates the tray icon with the left mouse button, triggering the icon’s activated()
signal. We will come back to this signal shortly.
The setIcon()
function sets the icon
property that holds the actual system tray icon. On Windows, the system tray icon size is 16x16; on X11, the preferred size is 22x22. The icon will be scaled to the appropriate size as necessary.
Note that on X11, due to a limitation in the system tray specification, mouse clicks on transparent areas in the icon are propagated to the system tray. If this behavior is unacceptable, we suggest using an icon with no transparency.
def iconActivated(self, reason): switch (reason) { QSystemTrayIcon.Trigger: = case() QSystemTrayIcon.DoubleClick: = case() iconComboBox.setCurrentIndex((iconComboBox.currentIndex() + 1) % iconComboBox.count()) break QSystemTrayIcon.MiddleClick: = case() showMessage() break default:
Whenever the user activates the system tray icon, it emits its activated()
signal passing the triggering reason as parameter. QSystemTrayIcon
provides the ActivationReason
enum to describe how the icon was activated.
In the constructor, we connected our icon’s activated()
signal to our custom iconActivated()
slot: If the user has clicked the icon using the left mouse button, this function changes the icon image by incrementing the icon combobox’s current index, triggering the setIcon()
slot as mentioned above. If the user activates the icon using the middle mouse button, it calls the custom showMessage()
slot:
def showMessage(self): showIconCheckBox.setChecked(True) selectedIcon = typeComboBox.itemData(typeComboBox.currentIndex()).toInt() QSystemTrayIcon.MessageIcon msgIcon = QSystemTrayIcon.MessageIcon(selectedIcon) if (selectedIcon == -1) { // custom icon icon = QIcon(iconComboBox.itemIcon(iconComboBox.currentIndex())) trayIcon.showMessage(titleEdit.text(), bodyEdit.toPlainText(), icon, durationSpinBox.value() * 1000) else: trayIcon.showMessage(titleEdit.text(), bodyEdit.toPlainText(), msgIcon, durationSpinBox.value() * 1000)
When the showMessage() slot is triggered, we first retrieve the message icon depending on the currently chosen message type. The MessageIcon
enum describes the icon that is shown when a balloon message is displayed. Then we call QSystemTrayIcon
‘s showMessage()
function to show the message with the title, body, and icon for the time specified in milliseconds.
macOS users note: The Growl notification system must be installed for showMessage()
to display messages.
QSystemTrayIcon
also has the corresponding, messageClicked()
signal, which is emitted when the user clicks a message displayed by showMessage()
.
def messageClicked(self): QMessageBox.information(None, tr("Systray"), tr("Sorry, I already gave what help I could.\n" "Maybe you should try asking a human?"))
In the constructor, we connected the messageClicked()
signal to our custom messageClicked()
slot that simply displays a message using the QMessageBox
class.
QMessageBox
provides a modal dialog with a short message, an icon, and buttons laid out depending on the current style. It supports four severity levels: “Question”, “Information”, “Warning” and “Critical”. The easiest way to pop up a message box in Qt is to call one of the associated static functions, e.g., information()
.
As we mentioned earlier, we reimplement a couple of QWidget
‘s virtual functions:
def setVisible(self, visible): minimizeAction.setEnabled(visible) maximizeAction.setEnabled(not isMaximized()) restoreAction.setEnabled(isMaximized() or not visible) QDialog.setVisible(visible)
Our reimplementation of the setVisible()
function updates the tray icon’s menu whenever the editor’s appearance changes, e.g., when maximizing or minimizing the main application window, before calling the base class implementation.
def closeEvent(self, event): #ifdef Q_OS_MACOS if (not event.spontaneous() or not isVisible()) { return #endif if (trayIcon.isVisible()) { QMessageBox.information(self, tr("Systray"), tr("The program will keep running in the " "system tray. To terminate the program, " "choose <b>Quit</b> in the context menu " "of the system tray entry.")) hide() event.ignore()
We have reimplemented the closeEvent()
event handler to receive widget close events, showing the above message to the users when they are closing the editor window. On macOS we need to avoid showing the message and accepting the close event when the user really intends to quit the application, that is, when the user has triggered “Quit” in the menu bar or pressed the Command+Q shortcut.
In addition to the functions and slots discussed above, we have also implemented several convenience functions to simplify the constructor: createIconGroupBox()
, createMessageGroupBox()
, createActions()
and createTrayIcon()
. See the desktop/systray/window.cpp
file for details.
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.