互聯(lián)網(wǎng)保險(xiǎn)經(jīng)紀(jì)公司十大排名哈爾濱推廣優(yōu)化公司
? 簡(jiǎn)介? ? ?
????????在 QML 中,將 JavaScript 字符串轉(zhuǎn)換為函數(shù)通常涉及使用 Function 構(gòu)造函數(shù)或 eval() 函數(shù)。但是,QML 的環(huán)境對(duì) JavaScript 的支持有一定的限制,因此不是所有的 JavaScript 功能都可以在 QML 中直接使用。?
????????以下介紹都是在Qt5.12.12環(huán)境下進(jìn)行的。
1、qml中使用 Function 構(gòu)造函數(shù):
在標(biāo)準(zhǔn)的 JavaScript 中,你可以使用 Function 構(gòu)造函數(shù)來(lái)從字符串創(chuàng)建函數(shù),如下所示:
var funcString = "return x + y";
var func = new Function('x', 'y', funcString);
console.log(func(1, 2)); ?// 輸出 3
?
2、qml中使用 eval()函數(shù):
eval() 函數(shù)可以執(zhí)行 JavaScript 代碼字符串。例如:
var funcString = "function add(x, y) { return x + y; }";
eval(funcString);
console.log(add(1, 2)); ?// 輸出 3
3、qt的C++中使用?QJSEngine
QJSEngine myEngine;
QJSValue fun = myEngine.evaluate("(function(a, b) { return a + b; })");
QJSValueList args;
args << 1 << 2;
QJSValue threeAgain = fun.call(args);
int result = threeAgain.toInt();
qml示例
main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQml 2.12Window {width: 1200height: 800visible: truetitle: qsTr("Hello World")objectName: "mainWindow"Rectangle{width: 800height: 300anchors.left: parent.leftanchors.top: parent.topborder.color: "blue"border.width: 1Rectangle {id : funcRectswidth: 700height: 200color: "lightgrey"border.color: "grey"anchors.verticalCenter: parent.verticalCenterTextArea {id: functionTextanchors.fill: parentwrapMode:TextEdit.WrapAnywhereanchors.margins: 2font.pointSize: 15focus: trueclip: truetext: "function add(x){return x+100;}"selectByMouse: true}}Rectangle {id : funcRects1width: 500height: 50color: "lightgrey"border.color: "grey"anchors.left: funcRects.leftanchors.top: funcRects.bottomRow{Label {id: inputKeytext: qsTr("輸入")font.pointSize: 15}TextInput {id: inputParamwidth: 100height: 30anchors.margins: 2font.pointSize: 15focus: trueclip: truetext: "120"selectByMouse: true}Button{text: "轉(zhuǎn)換"onClicked: {var funcString = functionText.text;eval(funcString);var result = add(inputParam.text);console.log(result);onputParam.text = result;}}Label {id: onputKeytext: qsTr("輸出")font.pointSize: 15}TextInput {id: onputParamwidth: 100height: 30anchors.margins: 2font.pointSize: 15focus: trueclip: truetext: ""selectByMouse: true}}}}
}
運(yùn)行結(jié)果:
結(jié)果1:
輸入的 inputParam.text 都按照字符串處理,所以輸出結(jié)果是 120100
結(jié)果2:
? ?
輸入的 inputParam.text 字符串在程序里面轉(zhuǎn)換為int,所以輸出結(jié)果是 220