Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

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

10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
o

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

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

o

Спасибо)

Comments

Only authorized users can post comments.
Please, Log in or Sign up
МБ
April 21, 2019, 9:40 a.m.
Моисей Бушуев

Qt - Test 001. Signals and slots

  • Result:0points,
  • Rating points-10
AA
April 17, 2019, 7:40 p.m.
Anton Ablin

Qt - Test 001. Signals and slots

  • Result:73points,
  • Rating points1
E
April 17, 2019, 6:16 p.m.
Evgeny

Qt - Test 001. Signals and slots

  • Result:100points,
  • Rating points10
Last comments
April 21, 2019, 4:22 p.m.
Евгений Легоцкой

Через метод setIcon table.horizontalHeaderItem(0).setIcon("qrc://path/to/icon.png")
April 21, 2019, 3:48 p.m.
Евгений Легоцкой

Добрый день! Спасибо за комментарий. Там действительно лучше будет сделать с инициализацией по умолчанию.
U
April 18, 2019, 3:37 p.m.
Unreal_man

А как иконку в хедер задать?
u
April 18, 2019, 2:15 a.m.
uaa

доброго времени,большое спасибо за пример для начинающего)при адаптации к своему проекту столкнулся с таким ньансом:в vepolyline.h в 47 строке нужна инициализация по умолчанию: int m_pointF...
E
April 11, 2019, 12:49 p.m.
Evgeny

Спасибо за ответ) У меня компоновщик на нее ругался просто. Оказалось, просто забыл Q_OBJECT в начале класса указать.
Now discuss on the forum
April 21, 2019, 4:16 p.m.
Евгений Легоцкой

Приветствую Нужно сохранять где-то выбранное значение, а потом восстанавливать его. Или использовать QSettings или добавить метод open(), в который передавать начальные значения для того...
R
April 19, 2019, 9:55 a.m.
RED_Spider

мені важко це зараз навіть перевірити, тому що знайшов коміт, це ще було в 2016 році, і цей код не буде працювати коректно зараз, єдине скажу що це були QThread
i
April 17, 2019, 3:03 p.m.
ilya.guzikov

BlinCT, на стороне ++ это делать необходимо так как в qml при использовании функции append происходит перерисовка всех точек лини(как я понимаю) и из-за этого при использовании больших массиво...
April 10, 2019, 11:20 a.m.
Алексей Внуков

может тоже кому надо будет - QML не принимает QVector<QVector<int>> , при попытке вывести полученый вектор QML показывает что это QVariant(QVector<QVector<int> ...
Join us in social networks

For registered users on the site there is a minimum amount of advertising