How To Pass Component Pointer From QML To C++?

What is the easiest way to pass a component pointer created in a QML file to C++? From Qt Documentation explanations we could take the QML file root object and then search for our component objectName. But it’s hard to keep sync the components objectName in both C++ codes and QML codes:

Just for Copy/Paste: qml_pass_objectName_example

auto const root = engine.rootObjects();
if(!root.empty())
{
    auto const obj = root.first()->findChild<test_item*>("testItem");
    if(obj)
    {
        c.setup_test(obj);
    }
    else
    {
        qDebug() << "Couldn't Cast";
    }
}
else
{
    qDebug() << "Empty";
}

I tried to pass the component from QML code on Component.onCompleted:

main.qml (for copy/paste: qml_pass_id_example/main.qml)
TestItem
{
        id: testItemId;
        Component.onCompleted: controller.setup_test(testItemId);
}
main.cpp (for copy/paste: qml_pass_id_example/main.cpp)
class controller : public QObject
{
    Q_OBJECT
  public slots:
    Q_INVOKABLE void setup_test(test_item* item)
    {
        item->f();
    }
};
#include "main.moc"

int main(int argc, char* argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    controller c;
    qmlRegisterType<test_item>("qml.pass.id", 1, 0, "TestItem");
    engine.rootContext()->setContextProperty("controller", &c);
    engine.load("qrc:/qml_pass_id_example/main.qml");
    return app.exec();
}

And I think this is much simpler than using objectName, but I couldn’t find any related documentation about passing the component’s ID to C++ functions. So my questions:

  1. What is the easiest way to passing the QML component pointer to C++?
  2. Is passing the QML component ID as the component C++ type pointer to the C++ function valid?

  • Qt: 6.2.0 and 5.15.2.
  • Compiler: GCC 11.1.0 and MSVC 2019.
  • Platforms: MS Windows and GNU/Linux

Answer

  1. The easy thing is debatable since it depends on the definition of what is easy or difficult for each case so I will not answer this question since it falls outside of SO.

  2. Yes, it is valid to export any QML object to C ++. The id is the reference to the object so you are not passing the name “testItemId” but you are passing a test_item object that has as identifier “testItemId”.

Note: It is recommended not to expose any QML object to C ++ (or do it for a minimum time) since its life cycle is managed by QML so it could be eliminated at any moment causing you to access pointers that no longer have associated objects. .