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.

Util.qml

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

main.qml

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

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.

Last updated

Was this helpful?