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

Pass an array of objects to c++ from qml



  • Trying to pass an array of objects to c++ from qml, but cannot find way to do it properly.

    qml sites

    function getCheckedAudioObject()
    {
        var results = []
        for(var i = 0; i < checkSongIndex.length; ++i){
            var obj = audioModel.get(checkSongIndex[i]) //audioModel is a ListModel
            results.push(obj)            
        }
    
        return results
    }
    

    c++ api

    Q_INVOKABLE void addAudioInformation(QVariantList const &audio_info)
    {
        qDebug()<<__func__<<audio_info.size(); //print 4, as expected
        qDebug()<<__func__<<audio_info[0].typeName(); //print QObject*
        qDebug()<<__func__<<audio_info[0].toMap(); //print Map()
    }
    

    How could I get the data of qml object from c++ api?Thanks


  • Moderators

    @tham said in Pass an array of objects to c++ from qml:

        qDebug()<<__func__<<audio_info[0].typeName(); //print QObject*
    

    The element is a QObject*.

        qDebug()<<__func__<<audio_info[0].toMap(); //print Map()
    

    You cannot convert a QObject* to a QMap.

    First, what does qDebug() << audio_info[0]; print? Is it your own custom QObject? If so, you can add a conversion function to the object.

    Otherwise, you can create a JavaScript object in QML and put this in your array. JavaScript objects can be treated as QVariantMap in C++:

    var results = []
    for(var i = 0; i < checkSongIndex.length; ++i){
        var qObj = audioModel.get(checkSongIndex[i])
        var jObj = {}
        jObj['property1'] = qObj.func1() // Your own function to extract data from the model's element
        jObj['property2'] = qObj.func2()
        results.push(jObj)
    }
    
    
    


  • @JKSH said in Pass an array of objects to c++ from qml:

    Is it your own custom QObject?

    No, it is ListModel of qml.


  • Moderators

    @tham said in Pass an array of objects to c++ from qml:

    @JKSH said in Pass an array of objects to c++ from qml:

    Is it your own custom QObject?

    No, it is ListModel of qml.

    Then you must convert each audioModel element to a custom JavaScript object. Pass an array of your custom JavaScript objects to C++.


Log in to reply