參考文章:https://www.cnblogs.com/lgxZJ/archive/2017/12/31/8158132.html
Qt和JavaScript的交互
Qt提供了對JS的良好支持,有兩種方式:
AScriptEngine- 4.3開始引入,現已被官方拋棄;
QJSEngine- 5.0引入;
- 封裝了
V8引擎;
Qt中執行腳本
QJSValue QJSEngine::evaluate(const QString &program, const QString &fileName = QString(), int lineNumber = 1);
program:腳本代碼
fileName/lineNumber:出錯的時候包含在出錯信息里
示例:
function test(){
return "123"
}
test();
QFile file("debug/JSTest.js");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return;
}
QString js_code = file.readAll();
file.close();
QJSEngine engine;
QJSValue result = engine.evaluate(js_code); //執行腳本
QString str_result = result.toString(); //"123"
Qt對腳本的動態控制
Qt中執行腳本,是將腳本代碼組成字符串,借此,可以動態控制腳本的代碼邏輯
QString js_code = QString("%1/%2").arg(10).arg(2);
qDebug()<<js_code; //10/2
QJSValue result = engine.evaluate(js_code);
qDebug()<<result.toString(); //5
配置JS的全局變量
QJSValue QJSEngine::globalObject() const; Returns this engine's Global Object.void QJSValue::setProperty(const QString &name, const QJSValue &value); Sets the value of this QJSValue's property with the given name to the given value.
通過globalObject()方法獲取引擎的全局對象,再使用setProperty()方法設置全局屬性,該屬性可以在js腳本中使用。
Qt的腳本化
QJSValue QJSEngine::newQObject(QObject *object); Creates a JavaScript object that wraps the given QObject object, using JavaScriptOwnership. Signals and slots, properties and children of object are available as properties of the created QJSValue.
使用newQObject函數,將Qt類封裝成js對象,集成在js的引擎中。
Qt的信號槽、屬性和子對象都可以封裝。
將Qt的類封裝起來,再通過全局屬性將其傳給js腳本,可以實現js和Qt的交互。
示例:
edit.setText("This is test");
QFile file("debug/JSTest.js");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return;
}
QString js_code = file.readAll();
file.close();
QJSEngine engine;
engine.globalObject().setProperty("edit", engine.newQObject(ui->lineEdit));
QJSValue result = engine.evaluate(js_code); //執行腳本
將ui->lineEdit控件封裝並傳給js,在腳本中調用,運行后,界面的lineEdit控件上會出現This is test文字。
