Qt编程之QtScript

时间:2023-08-05 09:05:26

需求是这样的:

需要给一个硬件接口测试些东西,用js来调用,js做成不同的独立模块分别测试不同的硬件接口,包括DMD内存,PCIE带宽等等。需要用一个exe来载入这些js文件分别调用测试模块。exe用Qt来做。就只能用QtScript模块了么。

QtScript是一个解释脚本的引擎 符合EMCAScript标准。

 void test_js::ExecuteJsFile(){

     QScriptEngine engine;

     if(JsFilePath.isEmpty()){
qDebug() << "No JavaScript File, Please check it!" <<endl;
return ;
} engine.installTranslatorFunctions(); Interfaces pcie; //pcie public add slot or check lineedit settext
QScriptValue scriptButton = engine.newQObject(&pcie);//生成C++对象的代理脚本对象
engine.globalObject().setProperty("button", scriptButton);//将对象注册到javascript QString fileName(JsFilePath);
QFile scriptFile(fileName);
scriptFile.open(QIODevice::ReadOnly);
QTextStream stream(&scriptFile);
QString contents = stream.readAll();
scriptFile.close(); QScriptValue result = engine.evaluate(contents,fileName); //parsing js format error
if(result.isError()) { qDebug() << "Error File Name is " << fileName << endl;
qDebug() << "Error line number is" << result.property("lineNumber").toInt32() << endl;
qDebug() << "Error Details is " << result.toString() << endl;
return ;
} qDebug() << fileName <<" 's Result: " << result.toInt32() <<endl; }
Interfaces 这个类的头文件是这样的:
 #ifndef INTERFACES_H
#define INTERFACES_H
#include <QtCore/QObject>
class Interfaces : public QObject{
Q_OBJECT
public slots:
void pcie_interface();
};
#endif

对应的实现文件:

 #include <QtCore/QDebug>
#include "test_interfaces.h" using namespace std; void Interfaces::pcie_interface(){
qDebug() << "called fuck!" << endl;
}

下面,javascript文件里面调用pcie_interface()函数,注意,以上pcie_interface函数必须声明成槽函数,不然会报错。

 //helloscript.js
button.pcie_interface();

references:

http://blog.csdn.net/guxch/article/details/7656846

http://blog.csdn.net/bbjjqq/article/details/6164291

http://blog.csdn.net/liuhongwei123888/article/details/6162159