Creating a Qt/QML application that uses the System Tray

Source code current not available.

So you want to build a Qt/QML application that puts an icon in the system tray and hides the icon on the taskbar when minimized.   This example will do just that.

Before you begin be aware that you'll need Qt 5.9.3.  I started with 5.9.1 but I found an issue with Qt's SystemTrayIcon class not giving the mouse context correctly.  It was fixed in Qt 5.9.3.

In short, I started by creating a basic Qt/QML application from their new project templates.  I created a QML file call SysTray that contains all necessary code to support the system tray icon functionality.  And you'll need to edit main.cpp and main.qml to wire it all up.

Things are briefly described here, please read the code to fully understand it.

In main.cpp you need to make sure you use QApplcation app(..).  Most likely you'll find QGuiApplciation app(..), remove it.  This has to be changed because QWidget functionality is needed to support the system tray icon.  I also added app.setWindowIcon(..) to give the application the same icon as the system tray.  Its not needed but it looks nice.

 QApplication app(argc, argv);
 app.setWindowIcon( QIcon(":/talk_icon.png") )

In the main.qml file I added the code to handle what happens when the application is minimized to the taskbar, see onVisibilityChanged, and I added code to activate the system tray icon, see SysTray.

onVisibilityChanged { .. }

SysTray { .. }

SysTray.qml is completely made up.  The initial code comes from QML's SystemTrayIcon  documentation.  Then modified to fit the example.

Since Qt's SysTrayIcon relies on some QWidget functionality so you'll need to add widgets to the project.   Add Qt += widgets to the project (.pro) file.

QT += widgets


How it works  


There are two parts.  There is the application hiding the taskbar icon and functionality behind the system tray icon. 

Hiding the application taskbar icon is relatively straight forward.  In the QML main application window I am monitoring the visibility state of the application, onVisibilityChanged.  'visibility' provides a property value of the current state.  When 'visibility' is 3, minimized state, the application has been minimize to the taskbar.  At that point you can call hide() and the application's icon will appear to disappear.

In the SysTray code there are two main parts, one that monitors when the mouse has clicked (ie activated) the system tray icon, onActivate, and the menu that may or may not appear at the system tray icon.  If you left click the system tray icon the application will be restored on the screen if not already there. 

If you right click the system tray icon the menu will pop up regardless of the state of the application's main window.  If the main window is hidden you can activated it.  In this example you can also close the application.  See the SystemTrayIcon documentation for more details.

No comments:

Post a Comment