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
OI

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

  • Result:40points,
  • Rating points-8
AD

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

  • Result:50points,
  • Rating points-4
m

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

  • Result:80points,
  • Rating points4
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 7:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 9:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 3:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 2:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 6:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
n
nklyDec. 27, 2024, 7:41 p.m.
Нужно запретить перемещение только некоторых итемов, остальные перемещать можно. У меня есть Представление QTreeView и древовидная модель QStandardItemModel подключенная к представлению. Итемы в модели QStandardItem. В разных ветках дерева могут быть элементы с одинаковым им…
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 10:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 2:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 10:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…

Follow us in social networks