需求:
使用Qt/C++ 调用js 脚本。Qt 调用lua 脚本性能应该是最快的,但是需要引入第三方库,虽然也不是特别麻烦,但是调用js脚本,确实内置的功能(C++ 调用lua 脚本-CSDN博客)
步骤:
1,pro 引入
QT+= core  qml2,调用js 脚本
#include <QCoreApplication>
#include <QtQml/QJSEngine>
#include <QtQml/QJSValue>
#include <QFile>
#include <QTextStream>
#include <QDebug>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QJSEngine jsEngine;
    QFile scriptFile("my.js");
    if (scriptFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream stream(&scriptFile);
        QString scriptCode = stream.readAll();
        jsEngine.evaluate(scriptCode);
        //调用js 函数 并传递参数
        QJSValue addFunction = jsEngine.globalObject().property("process");
        if (addFunction.isCallable()) {
            //16进制原始数据
            QJSValueList args;
            args << "1245";
            QJSValue result = addFunction.call(args);
            if (result.isString()) {
                QString re = result.toString();
                qDebug() << "Result of process function: " << re;
            } else {
                qDebug() << "Error: process function did not return a valid string.";
            }
        } else {
            qDebug() << "Error: 'process' function not found.";
        }
        scriptFile.close();
    } else {
        qDebug() << "Error: Unable to open the script file.";
    }
    return a.exec();
}
3,js 脚本编写
function process(data){
    var temStr = data.substring(0, 2)
    var humStr = data.substring(2,4)
    var temInt = parseInt(temStr,16)
    var humInt = parseInt(humStr,16)
    var re = "temperature:"+temInt.toString()+ " hum:"+humInt.toString()
    return re
}
4,效果

js 和lua对比:


目前Qt使用现成的js生态还很麻烦,在这种情况下,推荐使用lua脚本。
QML中能使用什么JS库_qml 使用node.js-CSDN博客



















