Evgenii Legotckoi
Evgenii LegotckoiJuly 5, 2017, 6:05 a.m.

QML - Tutorial 029. Registering a Singleton object to use "Static" methods in QML

The notion of static methods that are used in QML differs somewhat from the classical one in C ++, when static methods are created in the class that can be used referring to the class name, rather than to a specific object. In the case of QML, things are somewhat different. In order to use such methods in QML, which are present in the C ++ class, it is necessary to register a Singleton object that will provide the required methods, and these methods should no longer be static in themselves. They should at least be labeled with the Q_INVOKABLE macro so that they can be used in QML.

To register Singleton , you need to use the qmlRegisterSingletonType function, which in addition to the standard parameters that are passed to qmlRegisterType, you must also pass the static singletonProvider function, which you also write yourself.


Project structure

Create a Qt Quick project that will contain the following files:

  • SingletonQMLCpp.pro - Project profile
  • main.cpp - File with main function
  • main.qml - Main qml file
  • singletonclass.h - Singleton header file
  • singletonclass.cpp - Singleton source file

The project profile will be created by default and will not be changed.

main.cpp

Let's start with the file main.cpp, in which we will register the object of the future singleton.

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml> // We connect to use qmlRegisterSingletonType

#include "singletonclass.h" // We connect the header file SingletonClass

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

    // Register the singleton object through the function singletonProvider, that is, we pass the pointer to it as an argument.
    qmlRegisterSingletonType<SingletonClass>("SingletonClass", 1, 0, "SingletonClass", singletonProvider);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

singletonclass.h

In the header file, define enum, which we will use to get certain messages through the "static" getMessage method in the QML layer. In the same file, we define the static function singletonProvider , which will create a singleton instance.

#ifndef SINGLETONCLASS_H
#define SINGLETONCLASS_H

#include <QObject>
#include <QQmlEngine>
#include <QJSEngine>

class SingletonClass : public QObject
{
    Q_OBJECT
public:
    explicit SingletonClass(QObject *parent = nullptr);

    enum class Message {
        Info,
        Debug,
        Warning,
        Error
    };
    // Enum registration for use in QML
    Q_ENUM(Message)

    // To use this method in QML, declare it in Q_INVOKABLE
    Q_INVOKABLE QString getMessage(Message message);

signals:

public slots:
};

static QObject *singletonProvider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    Q_UNUSED(engine)
    Q_UNUSED(scriptEngine)

    SingletonClass *singletonClass = new SingletonClass();
    return singletonClass;
}

#endif // SINGLETONCLASS_H

Note that getMessage does not have to be static to act as a static Type method in QML.

singletonclass.cpp

This file provides the implementation of the getMessage method.

#include "singletonclass.h"

SingletonClass::SingletonClass(QObject *parent) : QObject(parent)
{

}

QString SingletonClass::getMessage(SingletonClass::Message message)
{
    switch (message)
    {
        case Message::Info:
            return "This is Info Message";
        case Message::Debug:
            return "This is Debug Message";
        case Message::Warning:
            return "This is Warning Message";
        case Message::Error:
            return "This is Error Message";
        default:
            return "Nothin not found";
    }
}

main.qml

And now let's use this singleton type in QML.

import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

import SingletonClass 1.0 // Connect Singleton


Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Singleton Class")

    ListView {
        anchors.fill: parent
        delegate: Item {
            height: 48
            width: parent.width
            Text {
                anchors.fill: parent
                text: model.text

                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
            }
        }

        model: listModel
    }

    ListModel {
        id: listModel

        // There is no way to use methods and functions directly for property in ListElement, so this hack is used
        Component.onCompleted: {
            listModel.append({'text': SingletonClass.getMessage(SingletonClass.Info)})
            listModel.append({'text': SingletonClass.getMessage(SingletonClass.Debug)})
            listModel.append({'text': SingletonClass.getMessage(SingletonClass.Warning)})
            listModel.append({'text': SingletonClass.getMessage(SingletonClass.Error)})
        }
    }
}

Conclusion

As a result, an application will be received that will display four messages in its window.

Thus, through the singleton object in QML, the ability to use cpp methods as static is added.

Download archive with project

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!

3
  • Oct. 1, 2018, 3:05 p.m.

In the debugger, I could not manage to see if the constructor is called once for all or if is called at every occurence from QML. Do you know?

Evgenii Legotckoi
  • Oct. 5, 2018, 8:11 a.m.

For QML constructor will be called once.

It works some differently from classic Singleton, but instance will be one.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
l
  • laei
  • April 23, 2024, 6:19 a.m.

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

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 6:17 a.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
e
  • ehot
  • March 31, 2024, 11:29 a.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
Last comments
k
kmssrFeb. 8, 2024, 3:43 p.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, 7:30 a.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, 5:38 a.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. 18, 2023, 6:01 p.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
G
GarApril 22, 2024, 2:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 4:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 3:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 13, 2024, 11:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 1:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks