Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Adding a new component definition in a class method to the scene



  • Hi,

    there's a class woman. It is registered in QML system.
    main.qml contains the object definition with a signal handler.
    The handler calls c++ method which should add a new button into the scene.

    I need to find the root object - the window in the main.qml to become a parent for the new button.
    How do you find a root object?

    Here's the method:
    @
    extern QQuickWindow *window;
    void woman::add_hip()
    {
    setProperty("hip", 87);

    QQmlEngine *engine = QtQml::qmlEngine(this);
    
    // 1. Define a QML component.
    QQmlComponent *readHipComp = new QQmlComponent(engine);
    readHipComp->setData("import QtQuick.Controls 1.2\n\
                         Button {\n\
                             anchors.top: addHipBtn.top\n\
                             anchors.left: addHipBtn.left\n\
                             anchors.margins: 3\n\
                             text: \"Hip value\"\n\
                             onClicked: {\n\
                                 msgDlg.text = woman.hip\n\
                                 msgDlg.open()\n\
                             }\
                         }", QUrl());
    // 2. Create the component instance.
    QQuickItem *readHipBtn = qobject_cast<QQuickItem *>(readHipComp->create());
    // 3. Add the instance to the scene.
    readHipBtn->setParentItem(qobject_cast<QQuickItem *>(engine->rootContext()->contextObject()));
    

    readHipBtn->setParentItem(window->contentItem());
    }
    @

    throws
    <Unknown File>: ReferenceError: addHipBtn is not defined
    <Unknown File>: ReferenceError: addHipBtn is not defined.

    It is added to GUI but it does not see other main.qml objects.


  • Moderators

    Hi,

    If I'm not mistaken you can pass the engine object to the class and then find the root object there.
    @
    //main.qml
    Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    }

    //main.cpp
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
    QObject *rootObject= engine.rootObjects().first();
    //rootObject will point to Window
    @

    In your case you can either pass rootObject to your class or pass engine to the class so that you can find root element there.


Log in to reply