QML: how to pass a javascript function as an argument in another function

I have a QML code like 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();
    }
}

in normal javascript this works cool, but when I use this code in QML, the bad thing visitFun always is of type undefined, and it does not work.

any idea how to make this work?

+4
source share
2 answers

In QML's internal functions, your self is of type QQuickItem, while a regular JS object (created using "new Object ()" or "{" prop ":" value "}", for example, is of type QJsValue . And "I" is not a variable name, it is a QML id, remember that defference.

QML \ , , "" JS. "typeof" ( "" JS ), - :

// Or simply "return obj.children" - but function become useless than.
if(obj.children)
        return true;
    else
        return false;

- "children" QML "list", .

, - QML, - .

+1

QtQuick 2

Item {  //<-- declaration
  id : item
  property variant fun 
}
item.fun : Qt.binding(function(){doSomething()})  //<--defintion

item.fun // <-- invocation without braces 

, .

a , , Button:

---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 - ;). , , .

0

All Articles