qml and creating multiple c++ qml objects from one template object
-
wrote on 28 Aug 2018, 19:39 last edited by
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_itemand another menu with more on_off_items
item
on_off_item
on_off_itemso 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. -
wrote on 28 Aug 2018, 23:26 last edited by
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-methodAnd 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-transitionsYou might find you're making it more complicated (but again, I already know I don't understand what you want exactly).
-
wrote on 30 Aug 2018, 18:43 last edited by
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:
- your object does not have any relationships with other objects, e.g. there are no bindings pointing to your object.
- 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 useQMetaObject::newInstance()
to create a clone of the obj.I don't know if that works for QQuickItem though. Good luck!
1/3