Evgenii Legotckoi
July 5, 2017, 5:14 p.m.

QML - Tutorial 030. Registering a QML Type as a Singleton object

In addition to C ++ classes in QML, Singleton can also use QML types, which are separate QML files.

This is also used by qmlRegisterSingletonType , but in order for this type to work as a singleton of the object, it is necessary to register the pragma Singleton in the QML file itself.

Let's make a small application that will also output several messages, while messages will be picked up through the Singleton QML Type method.


Project structure

  • SingletonQML.pro - project profile
  • main.cpp - File with main function
  • main.qml - Main QML file
  • Util.qml - Singleton QML

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

main.cpp

As the Singleton object use the file Util.qml. To make it a Singleton, it must be registered with qmlRegisterSingletonType, and also specify the pragma Singleton directive in it. First, we will register it.

  1. #include <QGuiApplication>
  2. #include <QQmlApplicationEngine>
  3. #include <QtQml> // We connect to use the qmlRegisterSingletonType function
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7. QGuiApplication app(argc, argv);
  8.  
  9. // We register the qml file by specifying its path.
  10. qmlRegisterSingletonType(QUrl("qrc:/Util.qml"), "Util", 1, 0, "Util");
  11.  
  12. QQmlApplicationEngine engine;
  13. engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
  14. if (engine.rootObjects().isEmpty())
  15. return -1;
  16.  
  17. return app.exec();
  18. }

Util.qml

In this file, be sure to specify the directive pragma Singleton.

  1. pragma Singleton // We indicate that this QML Type is a singleton
  2. import QtQuick 2.0
  3.  
  4. Item {
  5. function getMessage(messageNumber)
  6. {
  7. switch(messageNumber)
  8. {
  9. case 1:
  10. return "First Message"
  11. case 2:
  12. return "Second Message"
  13. case 3:
  14. return "Third Message"
  15. default:
  16. return "Nothing found"
  17. }
  18. }
  19. }

main.qml

And now we use the singleton object to output text using this function.

  1. import QtQuick 2.5
  2. import QtQuick.Window 2.2
  3. import QtQuick.Controls 1.4
  4.  
  5. import Util 1.0 // Thus, the import of QML singleton
  6.  
  7.  
  8. Window {
  9. visible: true
  10. width: 640
  11. height: 480
  12. title: qsTr("Singleton Class")
  13.  
  14. ListView {
  15. anchors.fill: parent
  16. delegate: Item {
  17. height: 48
  18. width: parent.width
  19. Text {
  20. anchors.fill: parent
  21. text: model.text
  22.  
  23. verticalAlignment: Text.AlignVCenter
  24. horizontalAlignment: Text.AlignHCenter
  25. }
  26. }
  27.  
  28. model: listModel
  29. }
  30.  
  31. ListModel {
  32. id: listModel
  33.  
  34. Component.onCompleted: {
  35. // The appeal to the singleton method looks like a call to the static method
  36. listModel.append({'text': Util.getMessage(1)})
  37. listModel.append({'text': Util.getMessage(2)})
  38. listModel.append({'text': Util.getMessage(3)})
  39. listModel.append({'text': Util.getMessage(4)})
  40. }
  41. }
  42. }

Conclusion

In this way, you can use singleton QML objects to emulate the use of static methods, and this is the right approach for working with similar functionality.

Download archive with project

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup