Nominate our 2022 Qt Champions!

MyQuickItem gets loaded twice on accessing its object in main.cpp

  • Hi Guys: I have a QtApp which many quick items in qml files. One of quick items is MyQuickItem which is embedded in qml/pages/SomePage.qml. MYQuickItem has a function I need to set some data into & I am trying to get a valid instance to MyQuickItem. I get a instance by doing the following in my main.cpp but the problem is that the constructor of MyQuickItem gets called twice because view.setSource & engine.load both called in main.cpp.

    My main.cpp

    int main(int argc, char *argv[]) 
      QQmlApplicationEngine engine;
      qmlRegisterType<MyQuickItem>("MyQuickItem", 1, 0, "MyQuickItem");
      QQuickView view;
      //Mainpage.qml is where MyQuickItem is located. Its sort of a child page of main.qml 
      QObject *object = view.rootObject();
      QObject *rect = object->findChild<QObject*>("myQuickItem"); 
      MyQuickItem* quickItem = qobject_cast<MyQuickItem*>(rect);
      return app.exec();

    My MainPage.qml

    import MyQuickItem 1.0
    MyQuickItem {
      id: myQuickItemID
      visible: true
      objectName: "myQuickItem"


    class MyQuickItem : public QQuickItem {
      SetCppObject(MyCppLibApiClass cppObject);
      MyCppLibApiClass m_cppObject;

    Can you please suggest how I can get a valid instance to MyQuickItem without creating it anew & thus avoid MyQuickItem's constructor getting called twice?

  • I got this working by doing the followind way of acquiring the quickItem object very much after help from this forum in my previous questions.

    QQuickItem *myItem = engine.rootObjects()[0]->findChild<QQuickItem *>("myQuickItem")

  • Lifetime Qt Champion


    Since you solved the problem, please mark the thread as solved using the "Topic Tools" button so that other forum users may know a solution has been found :)

  • surely yes. @p3c0 @SGaist thanks for the support guys

Log in to reply