Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Alternative method for qmlRegisterSingletonInstance method in qt 5.12.9.



  • I have a project which I need to compile in both 5.15.0 for an embedded system and 5.12.9 for android (due to api level constraints used in the device).
    I started the development using 5.15.0 and have used the neat function qmlRegisterSingletonInstance to pass the data to the qml only to realise that it is not supported in 5.12.9.
    The data I am passing has a Q_PROPERTY(QList<QList<CustomClass>>) which is being used as a model in the repeater and it works in case of qmlRegisterSingletonInstance.
    For 5.12.9 I have tried using qmlRegisterSingletonType and qmlRegisterUncreatableType along with rootContext->setContextProperty. Using these methods the repeater shows count as 0.
    Is there any way I can copy the functionality provided by qmlRegisterSingletonInstance in 5.12.9?

    Minimal example:

    // In case of 5.15
    QScopedPointer dataHolderPtr<DataHolder>(new DataHolder);
    qmlRegisterSingletonInstance<DataHolder>("DataHolder", 1, 0, "DataHolder",dataHolderPtr->get());
    
    //In case of 5.12.9
    static QScopedPointer<DataHolder> *dataHolderPtr;
    int main(int argc, char *argv[]) {
    ...//Default code
    
    dataModelPtr= new QScopedPointer<DataHolder>(new DataHolder);
    qmlRegisterSingletonType<DataHolder>("DataHolder", 1, 0, "DataHolder",getDataHolder);
    QQmlContext *rootContext = engine.rootContext();
    rootContext->setContextProperty("DataHolder", dataHolderPtr->get());
    
    ...//Other stuff
    }
    static QObject* getDataModel(QQmlEngine *engine, QJSEngine *scriptEngine)
    {
        Q_UNUSED(engine)
        Q_UNUSED(scriptEngine)
        qDebug()<< Q_FUNC_INFO<<dataHolderPtr->get()->count()<<endl; //This is printing correct count here but the same property returns 0 in qml.
        return dataHolderPtr->get();
    }
    


  • For someone facing a similar issue, I did not find a direct solution,

    According to the table
    https://doc.qt.io/qt-5/qtqml-cppintegration-data.html#sequence-type-to-javascript-array
    QList<CustomClass> is not yet supported in QML. Due to this reason I had to convert the QList<QList<CustomClass>> to QVariantMap<string,QVariantList<QVariantList<QVariantMap>>>

    And while using the values in qml use the bracket notation instead of the dot notation.