旧项目运行在Qt4.x上,要加上一个脚本逻辑,只能上Qt Script.(建议新项目使用QJSEngine)
QT += script
#include <QtScript>
int cpp_func(int a, int b) { return a + b; } QScriptValue cpp_func_wrapper(QScriptContext *ctx, QScriptEngine *eng) { int a = ctx->argument(0).toInt32(); int b = ctx->argument(1).toInt32(); return cpp_func(a, b); }
QScriptEngine engine; //向js中传递全局可用数据 engine.globalObject().setProperty("name", "liyangyao"); //向js中传递全局可用函数指针 (需要经过一层包装, 符合签名) QScriptValue cpp_func_ref = engine.newFunction(cpp_func_wrapper); engine.globalObject().setProperty("cpp_func", cpp_func_ref); //载入js QString script = readScript(":/script.js"); QScriptValue object = engine.evaluate(script); if (object.isError()) { qDebug()<<"line:"<<object.property("lineNumber").toInt32()<<" error:"<<object.toString(); return 0; } //调用js中的全局函数 qDebug()<<"execute script time:"<<time(NULL); QScriptValue func = engine.globalObject().property("js_func"); if (func.isValid()) { QScriptValue result = func.call(object, QScriptValueList()<<17); qDebug()<<"js_func return->"<<result.toString(); //获取js中的全局变量 qDebug()<<"context="<< engine.globalObject().property("context").toString(); } else{ qDebug()<<"js_func is not valid"; }