Qt编程之QtScript

需求是这样的:

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

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

 1 void test_js::ExecuteJsFile(){
 2 
 3     QScriptEngine engine;
 4 
 5     if(JsFilePath.isEmpty()){
 6         qDebug() << "No JavaScript File, Please check it!" <<endl;
 7         return ;
 8     }
 9 
10      
11     engine.installTranslatorFunctions();  
12 
13     Interfaces pcie;  //pcie  public add  slot  or  check lineedit settext
14     QScriptValue scriptButton = engine.newQObject(&pcie);//生成C++对象的代理脚本对象  
15     engine.globalObject().setProperty("button", scriptButton);//将对象注册到javascript  
16     
17     QString fileName(JsFilePath);  
18     QFile scriptFile(fileName);  
19     scriptFile.open(QIODevice::ReadOnly);  
20     QTextStream stream(&scriptFile);  
21     QString contents = stream.readAll();  
22     scriptFile.close();  
23     
24     QScriptValue result = engine.evaluate(contents,fileName);
25 
26     
27 
28     //parsing js format error
29     if(result.isError()) {
30         
31 
32         qDebug() << "Error File Name is "  << fileName << endl;
33         qDebug() << "Error line number is" << result.property("lineNumber").toInt32() << endl;
34         qDebug() << "Error Details is "    << result.toString() << endl;
35         return ;  
36     }  
37     
38     qDebug() << fileName <<" 's Result: " <<  result.toInt32() <<endl;  
39 
40 }
Interfaces 这个类的头文件是这样的:
1 #ifndef INTERFACES_H
2 #define INTERFACES_H
3 #include <QtCore/QObject>
4 class Interfaces : public QObject{
5     Q_OBJECT
6   public slots:
7       void pcie_interface();
8 };
9 #endif

对应的实现文件:

1 #include <QtCore/QDebug>
2 #include "test_interfaces.h"
3 
4 using namespace std;
5 
6 void Interfaces::pcie_interface(){
7     qDebug() << "called fuck!" << endl;
8 }

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

1 //helloscript.js  
2 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

原文地址:https://www.cnblogs.com/foohack/p/3973204.html