Nominate our 2022 Qt Champions!

Is possible to call from C++ a javascript function inside .js file?

  • Hi all

    The way to call from C++ a javascript function inside a QML item is well know using invokeMethodwith a object pointer. However QML allow to store functions inside a separate .js file and call from item by declaring as:

    import "MyFile.js" as MyFile

    As in the topic, is possible to call function inside .js file from C++. I think no since .js file is not an item and doesn't have a direct pointer but just in case I ask if exist some workaround.
    Thank you

  • Qt Champions 2016

    Well, there has a workaround / dirty hack for this problem.

    Let's say you have a MyFile.js with following content:

    .pragma library
    function hello() {

    You may call the hello() function from c++ by

        QQmlEngine engine;
        QJSValue value = engine.evaluate(QtShell::cat("MyFile.js") + ";hello"); // QtShell is not a part of Qt library. It provides a cat() which is same as Unix's cat command; // Print "Hello"

  • Hi
    Thank you for the suggestion but this solution require to create a object "pointer" to each single functions inside .js file, that is really unpratical solution. It seem you confirm there is no way to access .js functions like single item. I'll reorganize the code in other way...

Log in to reply