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 Updated to NodeBB v4.3 + New Features

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 3.0k Views 2 Watching
  • 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.
  • deleted57D Offline
    deleted57D Offline
    deleted57
    wrote on 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
    • benlauB Offline
      benlauB Offline
      benlau
      Qt Champions 2016
      wrote on 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
      • deleted57D Offline
        deleted57D Offline
        deleted57
        wrote on 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

        • Login

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