Connecting QML and C++



  • How do you connect qml and mainwindows.cpp ?


  • Moderators



  • you can in .cpp file, that derives from QWidget:
    @
    QDeclarativeView *view = new QDeclarativeView(this);
    view->setSource("qml/NomeProgramma/qmlfile.qml");
    QObject *obj = view->rootObject();
    connect(obj, SIGNAL(signal_fromQML(QString, int)), this, SLOT(slot_fromCpp(QString, int)));
    obj->setProperty("propertyFromQML", QVariant::fromValue("ValueThatComesFromCppFile"));
    view->show();
    this->show();
    @

    if you want to know something about lists from cpp to qml, you should have a view on qml data model!! ;)



  • You can also set context properties and use the Q_INVOKABLE macro in your C++ Q_Object derived class.

    @

       class customObject : public QObject
       {
            Q_OBJECT
            public: 
            ...constructor/destructor/assignmentOperator/copyConstructor...(standard functions you should implement)
    
            Q_INVOKABLE void someFunction();
    
            private:
            ...data
       };
    

    //-----------------------------------------------------------
    QDeclarativeView* view = newQDeclarativeView(this);
    QDeclarativeContext* rootContext = view->rootContext();

       rootContext->setContextProperty("NameViewableFromQML", &customObjectInstance);
    
       view->setSource("Something.qml");
     
      @
    

    Now you can do things like this in QML:

    NameViewableFromQML.someFunction();


Log in to reply
 

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