How to Pass the object from QML to CPP file?



  • Hi,
    I am developing an app.
    Query:
    How to pass the object from QML to CPP file, what will be object type in QT?

    Code:
    Login.QML
    function metPassObject()
    {

    var myCar = new Object();
    myCar.make = "Ford";
    myCar.model = "Mustang"
    myCar.year = 1969;

    objQtCPPSearchVOne.metPassObject(myCar);

    }

    .H file:
    Q_INVOKABLE void metPassObject (type parameter)- what will be the parameter type?

    .CPP file:
    void metPassObject(type parameter)
    {
    //How to access the object?
    }

    I am an .Net/C# guy, So my approach is based on that. Am I doing right code or If I am wrong, Pls correct me with concept.

    Thanks is Advance.



  • @Mathan-M I think, there are different ways for that, some of them:

    #1
    use QVariantMap on C++ side:
    Qml:

    function metPassObject()
    {
        var myCar = {make: "Ford"; model: "Mustang"; year: 1969};
        objQtCPPSearchVOne.metPassObject(myCar);
    }
    

    C++:

    Q_INVOKABLE void metPassObject (QVariantMap carMap){
        qDebug() << varMap.value("make").toString();
        qDebug() << varMap.value("model").toString();
        qDebug() << varMap.value("year").toInt();
    }
    

    #2
    Create C++ class derived from QObject with Q_PROPERTY. And register it to qml with qmlRegisterType():

    Car class:

    class Car : public QObject
    {
        Q_OBJECT
        Q_PROPERTY(QString make READ make WRITE setMake NOTIFY makeChanged)
        Q_PROPERTY(QString model READ model WRITE setModel NOTIFY modelChanged)
        Q_PROPERTY(int year READ year WRITE setYear NOTIFY yearChanged)
    
    //...
    // defining of setters, getters, signals, and data members for properies
    //...
    }
    

    Then, maybe somewhere in main.cpp:

    qmlRegisterType<Car>("my.car", 1, 0, "Car");
    

    Create car dynamically on qml side:

    function metPassObject()
    {
       var aCar = Qt.createQmlObject('import my.car1.0; Car{make: "Ford"; model:"Mustang"; year: 1969}', repeaterModel, "");
         objQtCPPSearchVOne.metPassObject(myCar);
    }
    

    and in C++ side:

    Q_INVOKABLE void metPassObject (Car* aCar){
        qDebug() << "Make: " << aCar->make();
        qDebug() << "Model: " << aCar->model();
        qDebug() << "year: " << aCar->year();
    }
    

    #3
    Send simpl types like string and int to C++ from Qml:

    Qml:

    function metPassObject()
    {
         objQtCPPSearchVOne.metPassObject("Ford", "Mustang", 1969);
    }
    

    And C++:

    Q_INVOKABLE void metPassObject (QString aMake, QString aModel, int aYear){
        Car* myCar = new Car(aMake, aModel, aYear);
        //...do smthg
    }
    


  • Hi @medyakovvit ,

    Now I can pass the objects.

    Thanks a Lot and really appreciate your efforts.

    Mathan


Log in to reply
 

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