问题描述
我有 QML 代码,例如这个代码
I have QML code, for example this code
Item {
id:self;
function update(){
var visitFunc = self.applyUpdate;
innerTraversal(self,visitFunc);
}
function reset(){
var visitFunc = self.applyReset;
innerTraversal(self,visitFunc);
}
function innerTraversal(obj, visitFun){
console.log(typeof visitFun);
if(obj!== self && visitFun && typeof visitFun ==="function")
visitFun(obj);
if(hasChilderns(obj)){
var objChilderns = obj.children;
for(var i=0 ; i< objChilderns.length ; i++){
innerTraversal(objChilderns[i]);
}
}
}
function hasChilderns(obj){
if(typeof obj.children !== 'undefined')
return true;
else
return false;
}
function applyReset(obj){
if(typeof obj.reset === 'function')
obj.reset();
}
function applyUpdate(obj){
if(typeof obj.update === 'function')
obj.update();
}
}
在普通的 javascript 中这很酷,但是当我在 QML 中使用这段代码时,坏事是 visitFun 的类型总是未定义,而且它不起作用..
in normal javascript this works cool, but when I use this code in QML the bad thing is visitFun always has type of undefined, and it does not work..
知道如何进行这项工作吗?
any idea how to make this work ?
推荐答案
在 QtQuick 2 中,您应该能够使用以下方法将函数绑定到属性
In QtQuick 2 you should be able to bind functions to properties using
Item { //<-- declaration
id : item
property variant fun
}
item.fun : Qt.binding(function(){doSomething()}) //<--defintion
item.fun // <-- invocation without braces
所以你可以传递一个带有泛型函数的对象作为参数.
So you could pass an object with a generic function as parameter.
一般来说,函数重载 a 也可以用来创建泛型函数,例如创建 Button 类型:
In general, function overloading a can also be used to create a generic function for example to create a Button type:
---Button.qml
Item {
function fun() {} //<-- declaration (empty dummy)
MouseArea {
anchors.fill: parent
onClicked: {
fun(); //<-- invocation
}
}
}
---
---main.qml---
Button {
id: button
function fun() { //<-- defintion by overloading
doSomething
}
}
---
单击按钮将激活其 onClick 处理程序并实际执行某些操作 ;).同样,您将使用通用函数而不是函数本身传递对象.
Clicking the button will activate its onClick handler and actually do something ;). Again, you would then pass the object with the generic function not the function itself.
这篇关于QML:如何将javascript函数作为参数传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!