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

QSystemTrayIcon, Qt, QML

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.
Support the author Donate
o

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

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

o

Спасибо)

Comments

Only authorized users can post comments.
Please, Log in or Sign up
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it
Donate

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways

PayPalYandex.Money
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
AS
May 26, 2020, 12:29 p.m.
Artem Sun-Dun-Chan

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
MN
May 25, 2020, 12:33 p.m.
Mitja Nagibin

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
f
May 25, 2020, 6:05 a.m.
falcon

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

  • Result:66points,
  • Rating points-1
Last comments
May 28, 2020, 4:14 p.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Ну в моём примере, который в статье сработало так model->setData(model->index(1, 1), 7); Поскольку model->index(1, 0) - это индекс колонки id, которая скрыта, поэтому…
MA
May 28, 2020, 4:08 p.m.
Mihail A

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Спасибо, завтра првоерю. А model->setData(model->index(1, 0), 7); Тоже заработало?
May 28, 2020, 4:06 p.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

Да, метод data всё-таки влиял, я переписал его так и заработало удаление QVariant TableModel::data(const QModelIndex &idx, int role) const{ if (role == Qt::BackgroundColorRole) {…
May 28, 2020, 3:49 p.m.
Evgenij Legotskoj

Django - Tutorial 011. Adding comments to the site based on Django

Он более функциональный и его функционал объективно лучше поддерживается Django. Из первого, что приходит на ум: Это наличие полей типа Array Поддержка полей для JSON …
May 28, 2020, 3:42 p.m.
progammist

Django - Tutorial 011. Adding comments to the site based on Django

а в чем явное преимущество postgresql над mysql?)
Now discuss on the forum
RG
May 28, 2020, 7:21 p.m.
Rovshan Gurbanov

Сборка под старые версии Android

У меня SDK почти все версии есть, NDK есть версии 10, 17, 21. Но собирается приложение только с NDK v21 под Android версии 7.0 и выше Версия Qt у меня 5.14.2
May 28, 2020, 8:58 a.m.
Evgenij Legotskoj

Освобождение памяти QMainWindow::setCentralWidget

Да, соглашусь. Просто удаление происходит позже, а не сразу.
May 28, 2020, 6:43 a.m.
Mihailll

При подключении к git как указать пароль?

Нужно сделать ssh-keygen и потом полученый из файла код скопировать в ssh ключ в бикбакете
F
May 28, 2020, 2:42 a.m.
Fidan

QML

Да, проблема ушла, спасибо.
May 1, 2020, 9:19 a.m.
Mihailll

Как в Qt в qmenu добавить scrollarea

Вот это наследованный класс меню. Но посути это обычное меню. #pragma once#include <QtWidgets>class TransMenu : public QMenu { Q_OBJECTpublic: TransMenu(QWidget* parent = …
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB