How to use my own javascript function in QML?

Viewed 34

I'm trying to call my own function to add an image source. The code is similar to this:

    function pics()
    {
        var source = "file:/home/nabil/Downloads/4.png"
        if (ident === "Nabil") {
            source = "qrc:images/Plane1.png" ;
        }
        return source;
    }

    Image
    {
        id: myIDImage
        source: myIDImage.pics() //here I am calling my function
        x: 0
        y: 0
        width: 30
        height: 30
    }

Can anyone please tell me the way of calling my own function?

1 Answers

You would do something like this:

import QtQuick 2.12

Item {
    function fibonacci(n){
        var arr = [0, 1];
        for (var i = 2; i < n + 1; i++)
            arr.push(arr[i - 2] + arr[i -1]);

        return arr;
    }
    TapHandler {
        onTapped: console.log(fibonacci(10))
    }
}

So, you do not need to call pics on myIDImage.

source: pics()

Moreover, in your case, you could just do something like:

source: (ident === "Nabil") ? "qrc:images/Plane1.png" : ""
Related