Ashif
Ashif

Reputation: 1684

To access QML component in C++ backend

I have a qml file with Rectangle. I would like to trigger the onClicked( ) from C++ back-end. So, How can I get access of QML component reference in C++/Qt backend?

Upvotes: 0

Views: 1012

Answers (1)

dtech
dtech

Reputation: 49329

You should use QObject::findChild() to locate the object, and simply invoke the signal as you would a nominal method.

But there is a catch, as QQuickRectangle itself is a private class, so it is not directly available for use in the C++ API. Also, it doesn't really have a clicked() signal, not unless you implemented one yourself. And if you did, it won't be part of the C++ interface.

Also, there is no onClicked() signal, the signal is clicked() and onClicked: is the handler hook.

However, you can still emit it using the Qt meta system, just use:

QObject * object = engine.rootObjects().at(0)->findChild<QObject *>("yourObjectName");
if (object) QMetaObject::invokeMethod(object, "clicked");

It will work even if the signal is implemented on the QML side, it will work even without casting to the concrete C++ type.

Now, if your object is not directly in the root object tree, you will not be able to find it and will have no choice but to pass a reference to it from the QML side to a C++ slot or invokable function.

Upvotes: 1

Related Questions