Jerry
Jerry

Reputation: 1812

How to create a global function in qml

I want to create a global function that can be called anywhere in my other qml files. Have tried to put a function inside of a rectangle, but it gives me syntax error in the next object. I don't want to use singleton because the syntax would be like Singleton.foobar. I just want to use foobar at anywhere in other qml.

Rectangle {
    function foobar(v) {
        return v * 2;
    }
}

ApplicationWindow { // syntax error here
}

Upvotes: 6

Views: 15339

Answers (2)

eSKon
eSKon

Reputation: 449

  1. Create C++ class with invokable function:
...
class MyCPPObject : public QObject
{
    Q_OBJECT
public:
...
Q_INVOKABLE bool funToCallFromJS(int any, QString args);
...
  1. Create MyCPPObject object in global space (rule is following: it must exist until engine exists (it's some simplification, but enough))
...
MyCPPObject cppobj;
...
  1. Use following code to export it to qml and js:
...
QJSValue wrapobj = engine.newQObject(&cppobj);
engine.globalObject().setProperty("cppFun", wrapobj.property("funToCallFromJS"));
...

wrapobj also must exists while engine exists (again simplification) 4. In qml and JS:

...
if(cppFun(127, "abc"))
    console.log("It works!");
...

Note: i used different names in qml space and cpp space just to show it's possible to rename cpp function when it used from js, but you can use same name, of course.

Upvotes: 4

derM
derM

Reputation: 13691

Define the function in your root-node (ApplicationWindow). This will be the last place, QML will look for a name, before it resorts to the C++-context properties.

See here to find out, how the names of variables and functions are resolved in QML.

It is not possible however to modify the global object, so true global JS-functions are not possible.

The more efficient approach however would be, to keep it always in one of the moste specific scopes, so referencing it with Identifyer.function() would be faster to look up. The singleton for libraries however is not the way to go. Look here for the usage of JS libraries.

Upvotes: 5

Related Questions