Calling a QML function from C++

断了今生、忘了曾经 提交于 2019-11-29 07:12:28

Thats what signals and slots are for. You can use the QML Connections for connecting arbitrary signals to arbitrary slots in QML.

http://qt-project.org/doc/qt-4.8/qml-connections.html

  Container {
            id: pinContainer
            objectName: "pinContObject"
            ...

            function addPin(lat, lon, name, address) {
                var marker = pin.createObject();
                marker.lat = lat;
                marker.lon = lon;
                ...
            }

            Connections {
                target: backend
                onDoAddPin: { 
                  addPin(latitude, longitude,name, address)
                }
            }
     }

and in C++ backend, all you have to do is

class Backend: public QObject {
signals:
    void doAddPin(float latitude, float longitude, QString name, QString address);

 ........
 void callAddPinInQML(){
     emit doAddPin( 12.34, 45.67, "hello", "world");
 }
}

MyItem.qml

import QtQuick 2.0
  Item {
    function myQmlFunction(msg) {
      console.log("Got message:", msg)
      return "some return value"
  }
}

main.cpp

QQmlEngine engine;
QQmlComponent component(&engine, "MyItem.qml");
QObject *object = component.create();

QVariant returnedValue;
QVariant msg = "Hello from C++";
QMetaObject::invokeMethod(object, "myQmlFunction",
    Q_RETURN_ARG(QVariant, returnedValue),
    Q_ARG(QVariant, msg));

qDebug() << "QML function returned:" << returnedValue.toString();
delete object;

This should works. Here i am calling a QML function from my C++ class.

user3545770

From Qt documentation:

http://qt-project.org/doc/qt-5/qtqml-cppintegration-interactqmlfromcpp.html#invoking-qml-methods

Calling QMetaObject::invokeMethod one will call proper slot, no matter if it is defined in C++ or QML.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!