Ben
Ben

Reputation: 9703

How to pass a callback function from qml to C++?

Related but different (I think): Pass qml function to c++ class to connect

I want to pass a callback function from qml into C++. That is, I want something like

// qml
myCPPObject.setCallback(function(result) { log("Got result", result) })

and on the C++ side, I'd want something like

// C++
void MyCPPObject::setCallback(std::function<void(QVariant)> cb) { m_cb = cb; }

Is there a way to do this? I'd be OK if it were a named function in qml or if it were something other than std::function on the C++ side.

Upvotes: 1

Views: 476

Answers (1)

Amfasis
Amfasis

Reputation: 4178

Yes that is possible with QJSValue, see Qt Doc and this example:

class myCppObject : QObject
{
    void setCallback(QJSValue func)
    {
        callback_ = func;
    }

    void whenCalled()
    {
        if(callback_.isCallable())
        {
            QJSValueList args;
            //args.append(...)
            callback_.call(args);
        }
    }
}

Only minor downside being that the arguments are not named, so you have to take care to define and adhere the interface on both sides.

Upvotes: 1

Related Questions