0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @tmcguire! I always thought that signals are asynchronous. If I was wrong so my problem is solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.