Registering a Singleton object to use “Static” methods in QML
Project structure
main.cpp
#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
singletonclass.cpp
main.qml
Conclusion

PreviousUsing enumerations in QML without C ++NextConnecting JavaScript files to other JavaScript files in a Qt / QML project
Last updated