How to create a global function in qml

Viewed 9352

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
}
2 Answers
  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.

Related