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) {
        Q_UNUSED(engine)
        Q_UNUSED(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:

    //QML
    property QtObject obj: MySingleTonObject 
    
    //C++
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
    QObject *obj = qvariant_cast<QObject *>(engine.rootObjects().first()->property("obj"));
    


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

    class FileIO: public QObject{
        Q_OBJECT
    public:
        //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){
        Q_UNUSED(engine)
        Q_UNUSED(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:

    FileIO::instance()->myFancyFunction();
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.