QT中 C++与 js 交互 (下):使用QJSEngine

1.主要代码:

C++:

 1 void QJSEngineDemo::initCenterControl()
 2 {
 3     QJSValue jsMetaObject = m_pJSEngin->newQMetaObject(&centerControl::staticMetaObject);
 4     m_pJSEngin->globalObject().setProperty("CenterControl", jsMetaObject);
 5 }
 6 void QJSEngineDemo::exeJsFun(QString& fun)
 7 {
 8     QJSValue jsObj = m_pJSEngin->globalObject().property("objGlobal");
 9     QJSValue result = jsObj.property(fun).call(QJSValueList()<<"11"<<"22");
10     printException(result);
11 }
12 
13 void QJSEngineDemo::printException(QJSValue& result)
14 {
15     if (result.isError())
16       qDebug()<< "Uncaught exception at line"
17               << result.property("lineNumber").toInt()
18               << ":" << result.toString();
19 }
20 
21 int main(int argc, char *argv[])
22 {
23     QApplication a(argc, argv);
24     preLoadScreen(NULL,a);
25 
26     QJSEngineDemo jsEngine;
27     jsEngine.initCenterControl();
28     jsEngine.loadJSFiles();
29     QString fun = "loadTools";
30     jsEngine.exeJsFun(fun);
31 
32     return a.exec();
33 }

JS:

 1 objGlobal.controlObject = null;
 2 
 3 /* use QJSEngine */
 4 objGlobal.loadTools = function() {
 5 
 6     if (!this.initialized) {
 7         this.controlObject = new CenterControl();
 8         this.controlObject.testSignal.connect(testSlot);
 9         this.controlObject.createMainWindow();
10 
11         this.initialized = true;
12     }
13 };
14 
15 function testSlot(){
16     if(this.controlObject !== null)
17         this.controlObject.printMsg("called testSlot");
18 }

2.完整工程代码:

https://github.com/SanSuiWanTong/QT_ToolBox

posted @ 2020-05-07 18:38  三岁玩童  阅读(2065)  评论(0编辑  收藏  举报