Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. Is possible to call from C++ a javascript function inside .js file?
Forum Update on Monday, May 27th 2025

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

Scheduled Pinned Locked Moved Unsolved QML and Qt Quick
3 Posts 2 Posters 2.9k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    deleted57
    wrote on 25 May 2017, 14:13 last edited by
    #1

    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

    1 Reply Last reply
    0
    • B Offline
      B Offline
      benlau
      Qt Champions 2016
      wrote on 25 May 2017, 14:52 last edited by
      #2

      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() {
          console.log("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
          value.call(); // Print "Hello"
      
      1 Reply Last reply
      0
      • D Offline
        D Offline
        deleted57
        wrote on 25 May 2017, 20:38 last edited by
        #3

        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...

        1 Reply Last reply
        0

        3/3

        25 May 2017, 20:38

        • Login

        • Login or register to search.
        3 out of 3
        • First post
          3/3
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved