Question

Suppose I have simple QML plugin. Periodically I check some state of my object, and in this step I want to query QML object from c++, in this way:

Plugin code (c++)

class MyItem : public QQuickItem
{
public:
    MyItem(QQuickItem *parent = 0) :
        QQuickItem(parent)
    {}
    void timerFunction(SomeObject * obj)
    {
        // here I need to call QML function to validate my object, may be in this way:
        callJSFunction("myFunction",obj); // that's what I need
        if(obj->approved) doSomething();
    }
}

QML file:

MyItem {
    id: myItem
    property bool someProperty
    function myFunction(obj)
    {
        obj.approved = someProperty;
    }
}

I cannot use signals just because call to JS must be in synchronous manner. I mean what I need is:

  • in c++ code timer calls to function timerFunction() with object to validate
  • inside timerFunction() I call to JS function and get result back
  • After it I continue to execute timerFunction()

So my question - is there some way to call JS function from C++ plugin object?

Was it helpful?

Solution

I cannot use signals just because call to JS must be in synchronous manner.

Signals in Qt by default are actually synchronous. When you emit a signal, all connected slots are called right away, and the emit statement only returns when all slots have executed. So in your case, make MyItem emit a signal and connect to that signal in QML. (The only exception is in multithreaded code, but I assume your MyItem instance lives in the same thread as the QML engine)

You can of course do it the other way around, and invoke JS functions from C++. I would advocate against that, since it breaks the layering - the QML layer should access the C++ layer, and not the other way around. Anyway, to call JS functions from C++, use QMetaObject::invokeMethod. For full details, have a look at the documentation about Interacting with QML Objects from C++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top