Evgenii Legotckoi
Evgenii LegotckoiNov. 1, 2015, 12:39 p.m.

QML - Lesson 008. How to work with system tray (QSystemTrayIcon)

When moving the application interface from Qt / C ++ to Qt / QML my hands reached and application icons in the system tray. The aim was to put an icon in the System Tray from C ++ to QML, partially or completely. The first option, which I realized, was a wrapper around QSystemTrayIcon with QMenu using a system of signals and slots . The solution is quite logical, given that in QML is not a facility, like MenuBar to System Tray. So we do a wrapper, which can interact in QML layer.

After the wrapper was implemented, I had the opportunity to consult with the programmer of Wargamming  - Constantine Lyashkevich , who recommended me to pay attention to what QML can have access not only to the signals and slots, and the parameters of the Q_PROPERTY , who also were in the class QSystemTrayIcon , that is, in fact it was only possible to register this class as the type layer in QML and try to write almost all the code on the QML. I checked the board and talked about by Constantine. As a result, he became interested in this problem and we spent the evening entertaining hour of attempts and jointly stuffed QSystemTrayIcon maximum in QML.

So in this article you will see two implementations to work with an icon in the system tray.

The resulting application will minimize to the System Tray by clicking the icon in the system tray, as well as by pressing the close button. But only in the event that will be active the special checkbox to control the folding process of the application window to the system tray, if the checkbox is not enabled, the application will be closed. Also, the application can be closed with an active checkbox menu item in the system tray icon.


First variant

Variant to work with the system tray through the wrapper class.

Projeect structure for System Tray

The project includes the following files:

  • QmlSystemTray.pro - the profile of the project;
  • main.cpp - the primary source file to launch the application;
  • systemtray.h - class header file to work with the system tray;
  • systemtray.cpp - class source code file to work with the system tray;
  • main.qml - file from the main application window;
  • logo-min.png - any icon that will be placed in the system tray.

QmlSystemTray.pro

TEMPLATE = app

QT += qml quick widgets

SOURCES += main.cpp \
    systemtray.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Default rules for deployment.
include(deployment.pri)

HEADERS += \
    systemtray.h

main.cpp

As in the tutorial on signals and slots make the declaration and initialization of the object of a separate Qt / C ++ class and set the access to it from Qml layer.

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSystemTrayIcon>

#include <systemtray.h>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;

    // We declare and initialize the class object to work with system tray
    SystemTray * systemTray = new SystemTray();
    QQmlContext * context = engine.rootContext();
    // Set access to an object of class properties in QML context
    context->setContextProperty("systemTray", systemTray);

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

systemtray.h

The header file declares the class SystemTray signals that will pass information to the QML, and QSystemTrayIcon object that will be interaction. In addition, we declare a handler interact with this icon.

#ifndef SYSTEMTRAY_H
#define SYSTEMTRAY_H

#include <QObject>
#include <QAction>
#include <QSystemTrayIcon>

class SystemTray : public QObject
{
    Q_OBJECT
public:
    explicit SystemTray(QObject *parent = 0);

signals:
    void signalIconActivated();
    void signalShow();
    void signalQuit();

private slots:
    /* The slot that will accept the signal from the event click on the application icon in the system tray
     */
    void iconActivated(QSystemTrayIcon::ActivationReason reason);

public slots:
    void hideIconTray();

private:
    /* Declare the object of future applications for the tray icon*/
    QSystemTrayIcon         * trayIcon;
};

#endif // SYSTEMTRAY_H

systemtray.cpp

Next we writes the source code for the class to work with System Tray, but realize only supply signals in the interaction with the menu items and the system tray icon. the signal processing logic is implemented in QML.

#include "systemtray.h"
#include <QMenu>
#include <QSystemTrayIcon>

SystemTray::SystemTray(QObject *parent) : QObject(parent)
{

    // Create a context menu with two items
    QMenu *trayIconMenu = new QMenu();

    QAction * viewWindow = new QAction(trUtf8("Развернуть окно"), this);
    QAction * quitAction = new QAction(trUtf8("Выход"), this);

    /* to connect the signals clicks on menu items to the appropriate signals for QML.
     * */
    connect(viewWindow, &QAction::triggered, this, &SystemTray::signalShow);
    connect(quitAction, &QAction::triggered, this, &SystemTray::signalQuit);

    trayIconMenu->addAction(viewWindow);
    trayIconMenu->addAction(quitAction);

    /* Initialize the tray icon, icon set, and specify the tooltip
     * */
    trayIcon = new QSystemTrayIcon();
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->setIcon(QIcon(":/logo-min.png"));
    trayIcon->show();
    trayIcon->setToolTip("Tray Program" "\n"
                         "Work with winimizing program to tray");

    /* Also connect clicking on the icon to the signal handler of the pressing
     * */
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}

/* The method that handles click on the application icon in the system tray
 * */
void SystemTray::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason){
    case QSystemTrayIcon::Trigger:
        // In the case of pressing the signal on the icon tray in the call signal QML layer
        emit signalIconActivated();
        break;
    default:
        break;
    }
}

void SystemTray::hideIconTray()
{
    trayIcon->hide();
}

main.qml

To access the properties of an object of the class SystemTray in the Qml layer prescribes object Connections, through which the connection to SystemTray object. to prescribe target property name, which was announced in the main.cpp file, when the engine is installed Qml access to the object through the system tray setContextProperty() method.

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Window 2.0

ApplicationWindow {
    id: application
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    // Chance to ignore the checkbox
    property bool ignoreCheck: false

    /* With help Connections object
     * set connections with System tray class
     * */
    Connections {
        target: systemTray
        // Сигнал - показать окно
        onSignalShow: {
            application.show();
        }

        // The signal - close the application by ignoring the check-box
        onSignalQuit: {
            ignoreCheck = true
            close();
        }

        // Minimize / maximize the window by clicking on the default system tray
        onSignalIconActivated: {
             if(application.visibility === Window.Hidden) {
                 application.show()
             } else {
                 application.hide()
             }
        }
    }

    // Test check box to control the closing of the window
    CheckBox {
        id: checkTray
        anchors.centerIn: parent
        text: qsTr("Enable minimizing to system tray during the window closing")
    }

    // Handler window closing event
    onClosing: {
        /* If the check box should not be ignored and it is active, 
         * then hide the application. Otherwise, close the application
         * */
        if(checkTray.checked === true && ignoreCheck === false){
            close.accepted = false
            application.hide()
        } else {
            Qt.quit()
        }
    }
}

Second variant

And now proceed to the second embodiment, which is written in collaboration with Konstantin Lyashkevich.

Project Structure

In this case, only the structure of the project will consist of:

  • QmlSystemTray.pro - the profile of the project;
  • main.cpp - the primary source file to launch the application;
  • main.qml - file of the main application window;
  • logo-min.png - any icon that will be placed in the system tray.

QmlSystemTray_2.pro

In this case, I recommend to pay attention to the modules that are connected in the project. Because without quickwidgets module do not work.

TEMPLATE = app

QT += qml quick widgets quickwidgets

SOURCES += main.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Default rules for deployment.
include(deployment.pri)

main.cpp

It is also necessary to connect the library to the QQuickWidget main.cpp source file. It is necessary to use qmlRegisterType function.

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QIcon>
#include <QQuickWidget>
#include <QSystemTrayIcon>
#include <QQmlContext>

// Declare a user-defined data type to work with an icon in QML
Q_DECLARE_METATYPE(QSystemTrayIcon::ActivationReason)

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlApplicationEngine engine; 

    // Register QSystemTrayIcon in Qml
    qmlRegisterType<QSystemTrayIcon>("QSystemTrayIcon", 1, 0, "QSystemTrayIcon");
    // Register in QML the data type of click by tray icon
    qRegisterMetaType<QSystemTrayIcon::ActivationReason>("ActivationReason");
    // Set icon in the context of the engine
    engine.rootContext()->setContextProperty("iconTray", QIcon(":/logo-min.png"));
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

main.qml

Next, we make declaring QSystemTrayIcon object and configure it in onCompleted method. Due to the fact that we have registered the type QSystemTrayIcon::ActivationReason, then the method onActivated we are able, depending on the type of value sent is reason to determine the response to mouse clicks on an application icon in the system tray. When we do a right click on the application icon in the system tray, there is a Menu . The menu is a function popup() . function feature is that it brings up a menu at the point where the mouse cursor, so the menu appears at the location of the system tray icons.

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Window 2.0
import QSystemTrayIcon 1.0

ApplicationWindow {
    id: application
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    // Registered in the system tray QML layer
    QSystemTrayIcon {
        id: systemTray

        // Initial initialization of the system tray
        Component.onCompleted: {
            icon = iconTray             // Set icon
            toolTip = "Tray Program
Работа со сворачиванием программы трей"
            show();
        }

        /* By clicking on the tray icon define the left or right mouse button click was. 
         * If left, then hide or open the application window. 
         * If right, then open the System Tray menu
         * */
        onActivated: {
            if(reason === 1){
                trayMenu.popup()
            } else {
                if(application.visibility === Window.Hidden) {
                    application.show()
                } else {
                    application.hide()
                }
            }
        }
    }

    // Menu system tray
    Menu {
        id: trayMenu

        MenuItem {
            text: qsTr("Maximize window")
            onTriggered: application.show()
        }

        MenuItem {
            text: qsTr("Exit")
            onTriggered: {
                systemTray.hide()
                Qt.quit()

            }
        }
    }

    // Test check box to control the closing of the window
    CheckBox {
        id: checkTray
        anchors.centerIn: parent
        text: qsTr("Enable minimizing to system tray during the closing the window")
    }
    onClosing: {
        /* If the check box should not be ignored and it is active, then hide the application. 
         * Otherwise, close the application
         * */
        if(checkTray.checked === true){
            close.accepted = false
            application.hide()
        } else {
            Qt.quit()
        }
    }
}

Conclusion

As a result of the work done, you will receive an application, which will be minimized to tray as the clicks on the icon in the system tray, and close the window by pressing the application button. Look, it would be like in the following figure.

Co-author of the article: Constantine Lyashkevich

Video

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

o
  • April 3, 2017, 5:13 p.m.

Здравствуйте. В первом варианте не выложен файл QmlSystemTray.pro без него как-то не полно.

Evgenii Legotckoi
  • April 4, 2017, 2:33 a.m.

Добрый день. Добавил QmlSystemTray.pro.

o
  • April 4, 2017, 2:34 a.m.

Спасибо)

Comments

Only authorized users can post comments.
Please, Log in or Sign up
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
FL

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 7:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 4:57 p.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 12:18 p.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 2:48 p.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks