参考:https://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html#invoking-qml-methods
一、调用说明
所有QML的函数(方法)都暴露在元对象系统中,并且在C++中可以使用QMetaObject::invokeMethod()调用。您可以指定参数的类型和冒号字符后的返回值,如下面的代码段所示。
二、QML代码
// MyItem.qml import QtQuick 2.0 Item { function myQmlFunction(msg: string) : string { console.log("Got message:", msg) return "some return value" } }
三、C++代码
// main.cpp QQmlEngine engine; QQmlComponent component(&engine, "MyItem.qml"); QObject *object = component.create(); QString returnedValue; QString msg = "Hello from C++"; QMetaObject::invokeMethod(object, "myQmlFunction", Q_RETURN_ARG(QString, returnedValue), Q_ARG(QString, msg)); qDebug() << "QML function returned:" << returnedValue; delete object;