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

qml and creating multiple c++ qml objects from one template object



  • If I have a qml file that describes the look of an on/off button,
    how can I findObject with c++ and use it to create multiple QQuickItem objects?

    I know I can do it using this...

        m_pQmlComponent = new QQmlComponent(pEngine,QUrl(pszQmlFilename));
        if (m_pQmlComponent)
        {
            //create a dynamic instance
            QObject *pObject = m_pQmlComponent->create();
    

    but what I need is a way to create the component using only the object found using findChild off the root object.

    For example: If I had a On/Off menu item call on_off_item
    and I had a menu with
    item
    on_off_item
    item
    on_off_item

    and another menu with more on_off_items
    item
    on_off_item
    on_off_item

    so now my c++ code has multple objects that use on_off_item as a template.
    but on_off_item will be listed just once in the qml file.



  • I can't understand your use case - I tried twice - that's ok.

    I'd direct you to look at dynamic qml createComponent and maybe with incubate
    http://doc.qt.io/qt-5/qml-qtqml-component.html#incubateObject-method

    And http://doc.qt.io/qt-5/qtqml-cppintegration-definetypes.html

    I don't personally have c++ instances spawned from QML but it's certainly possible.

    If you just wish to display differently for what's on and off etc, have you seen states and transitions?
    http://doc.qt.io/qt-5/qml-tutorial3.html and
    https://qmlbook.github.io/en/ch05/index.html#states-and-transitions

    You might find you're making it more complicated (but again, I already know I don't understand what you want exactly).



  • Do you want to clone an existing object in the object tree of a QML document? Is it that what you want? To my best knowledge, this is only possible under the following circumstances:

    1. your object does not have any relationships with other objects, e.g. there are no bindings pointing to your object.
    2. your object does not have any signal/slot connections. Or at least, you will have to reproduce them somehow after cloning.

    When you clone the object, make sure that you keep the same parent as the original one and you are using exactly the same type. Use obj->metaObject() to find out its type and use QMetaObject::newInstance() to create a clone of the obj.

    I don't know if that works for QQuickItem though. Good luck!


Log in to reply