在.qml中写一个函数
import QtQuick
import QtQuick.Controls
import MyObj 1.0Window {id: windowobjectName: "window"width: 480height: 480visible: truetitle: qsTr("Hello World")//目标函数function qmlFunc(i, s) {return "success"}Button {id: btnobjectName: "button"onClicked: {MyObject.func()}}
}
在main.cpp中调用
#include"myobject.h"#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QScreen>
#include <QObject>int main(int argc, char *argv[])
{QGuiApplication app(argc, argv);QQmlApplicationEngine engine;qmlRegisterSingletonInstance<MyObject>("MyObj", 1, 0, "MyObject", MyObject::getInstance());QObject::connect(&engine,&QQmlApplicationEngine::objectCreationFailed,&app,[]() { QCoreApplication::exit(-1); },Qt::QueuedConnection);engine.loadFromModule("updatePublisher", "Main");//获取部件auto list = engine.rootObjects();auto window = list.first();//调用函数QVariant res;QVariant arg_1 = 123;QVariant arg_2 = "Zhang San";QMetaObject::invokeMethod(window, "qmlFunc", Q_RETURN_ARG(QVariant, res), Q_ARG(QVariant, arg_1), Q_ARG(QVariant, arg_2));qDebug() << res;return app.exec();
}