我尝试在QML中启用JavaScript控制台。我在QML书的git储存库中尝试了Javascript Console示例。但是在控制台中输入第一个输入为错误值后,即使我输入了真值,结果也始终是不确定的(例如第一个输入:a = b,请输入,结果是未定义的,第二个输入:2 + 2,结果是“未定义”) 。但是,在控制台中输入真实值时,即使我输入了错误的值,它也能很好地工作。当我尝试修改javascript时,它不起作用。有可能修复它吗?谢谢!
main.qml:
import QtQuick 2.5
import QtQuick.Controls 1.5
import QtQuick.Layouts 1.2
import QtQuick.Window 2.2
import "jsconsole.js" as Util
ApplicationWindow {
id: root
title: qsTr("JSConsole")
width: 640
height: 480
ColumnLayout {
anchors.fill: parent
anchors.margins: 9
RowLayout {
Layout.fillWidth: true
TextField {
id: input
Layout.fillWidth: true
focus: true
onAccepted: {
root.jsCall(input.text)
}
}
Button {
text: qsTr("Send")
onClicked: {
root.jsCall(input.text)
}
}
}
Item {
Layout.fillWidth: true
Layout.fillHeight: true
Rectangle {
anchors.fill: parent
color: '#333'
border.color: Qt.darker(color)
opacity: 0.2
radius: 2
}
ScrollView {
id: scrollView
anchors.fill: parent
anchors.margins: 9
ListView {
id: resultView
model: ListModel {
id: outputModel
}
delegate: ColumnLayout {
width: ListView.view.width
Label {
Layout.fillWidth: true
color: 'green'
text: "> " + model.expression
}
Label {
Layout.fillWidth: true
color: 'blue'
text: "" + model.result
}
Rectangle {
height: 1
Layout.fillWidth: true
color: '#333'
opacity: 0.2
}
}
}
}
}
}
function jsCall(exp) {
var data = Util.call(exp);
outputModel.insert(0, data)
}
}
jsconsole.js:
.pragma library
var scope = {
}
function call(msg) {
var exp = msg.toString();
console.log(exp)
var data = {
expression : msg
}
try {
var fun = new Function('return (' + exp + ');');
data.result = JSON.stringify(fun.call(scope), null, 2)
console.log('scope: ' + JSON.stringify(scope, null, 2) + 'result: ' + result)
} catch(e) {
console.log(e.toString())
data.error = e.toString();
}
return data;
}