javascript function in QML



  • Why I'm not getting the desired result in the following code?

    Item {
        id: root
        width: 200
        height: 200
    
        function foo() {
            var l = 2+2;
        }
    
        Component.onCompleted: {
            var str = foo.toString();
            console.log(str)
        }
    }
    

    It's giving me function() { [code] } rather then function foo() { var l = 2+2; } .What's the reason for such behaviour?



  • Because you must use return in your function.
    Of course not need to convert function to String, check blow code :)

    Item {
            id: root
            width: 200
            height: 200
    
            function foo() {
                var l = 2 + 2;
                return l;
            }
    
            Component.onCompleted: {
                console.log(foo())
            }
        }
    
    


  • My desired output is function foo() { var l = 2+2; }.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.