Nominate our 2022 Qt Champions!

Qt: I defined and registered a QML singleton in C++. How do I access this singleton from C++?

  • I had no problems with defining and registering a QML singleton in C++, and using that singleton from QML. Now, however, I want to call methods on that singleton from C++ as well. How do I get access to the single instance that the singleton has?

    For now I've done the following hack:

    FileIO* fileIO;
    static QObject* fileIOSingletonTypeProvider(QQmlEngine *engine, QJSEngine *scriptEngine) {
        FileIO* instantiatedObj = new FileIO();
        ::fileIO = instantiatedObj;
        return instantiatedObj;
    // ...
    qmlRegisterSingletonType<FileIO>("FileIO", 1, 0, "FileIO", fileIOSingletonTypeProvider);

    So I store a global pointer to it at the point of instantiation.

    This works. Is there a proper way to do it, though?

  • Moderators

    @Stefan-Monov76 Another way would be to assign it to QtObject in QML and the access this property in C++. Something like:

    property QtObject obj: MySingleTonObject 
    QQmlApplicationEngine engine;
    QObject *obj = qvariant_cast<QObject *>(engine.rootObjects().first()->property("obj"));

  • @Stefan-Monov76 you could also use something like that:

    class FileIO: public QObject{
        //singleton type provider function for Qt Quick
        static QObject* fileIOSingletonTypeProvider(QQmlEngine *engine, QJSEngine *scriptEngine);
        //singleton object provider for C++
        static FileIO* instance();
        void myFancyFunction();
    QObject* FileIO::fileIOSingletonTypeProvider(QQmlEngine *engine, QJSEngine *scriptEngine){
        return FileIO::instance();
    FileIO* FileIO::instance() {
        static FileIO* fileIO = new FileIO();
        return fileIO;
    void FileIO::myFancyFunction(){
       //do something

    In that case you could get the singleton, with:


Log in to reply