0

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?

dtech
  • 47,916
  • 17
  • 112
  • 190
Ashif
  • 1,652
  • 14
  • 30

1 Answers1

1

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.

dtech
  • 47,916
  • 17
  • 112
  • 190
  • I have tried to call the slot of QML onPropertyNameChanged() from invokeMethod, but it is not handling, I think, signal can only be invoked. – Ashif Mar 30 '16 at 05:30
  • @Ashif - there is no such object `onSignalName` - this is just an assist provided to make declarative connections, it cannot be invoked. – dtech Mar 30 '16 at 10:51