如果我有一些JS代码作为文本,并且我在eval()
中调用它,那么我可以仅在eval()发生的范围内使用此语句定义的函数。据我所知,这意味着从eval创建的任何新的JS定义对QML的其余部分都是不可见的。考虑以下QML信号处理程序:
Item {
id: testitem
onThesourceChanged: {
eval(thesource)
testfunction()
}
}
testfunction()
在文本"源"中定义,确实在上面的信号处理程序中工作,打印出一些测试文本;但是它不在QML元素的范围内,因此就我所知,不能再调用它了。我尝试过各种各样的想法,比如把eval()
放在一个函数中,或者在Component.onCompleted
里面,等等,但我似乎无法弄清楚如何让eval()
创建的任何东西被识别为父QML元素的一部分。
例如,我希望能够调用testitem.testfunction()
-但它不是在这个处理程序的范围之外定义的。
您需要在稍后要访问的范围内声明该变量。使用eval()
在子作用域中初始化它:
import QtQuick 2.1
Rectangle {
width: 360
height: 360
MouseArea {
anchors.fill: parent
onClicked: {
testitem.thesource = "myfunction = function(text) { return text.toLowerCase() }"
}
}
Text {
id: testitem
property var myfunction: function(text) { return text.toUpperCase() }
property var thesource;
anchors.centerIn: parent
text: myfunction("Kullo – Secure Messaging")
onThesourceChanged: {
eval(thesource);
text = myfunction("Kullo – Secure Messaging")
}
}
}