How can I create qml dynamically with c++ and preverse the context of root [SOLVED]
I create QDeclarativeItem dynamically with c++ that I attach to my root but the context of each is diferente
QDeclarativeComponent* component = new QDeclarativeComponent(_view->engine(), "image.qml");
QDeclarativeItem* item = qobject_cast<QDeclarativeItem*>(component->create());
qWarning() << " context for root: " << qmlContext(_view->rootObject());
qWarning() << " context for image " << qmlContext(item);
the result is:
context for root: QDeclarativeContext(0x13e54a0)
context for image: QDeclarativeContext(0x13e3ea0)
I also can't find the item on root with this function
_view is my QDeclarativeView and "image1" is the id of my qml file
Contexts will be different but you should be able to see contextProperties set in rootContext in image context.
Be aware that findChild takes objectName as argument not id. You should set
in yor image.qml file and everything should work as expected.
You should also add:
to your code ( http://doc.qt.digia.com/qt/qdeclarativeengine.html#ObjectOwnership-enum )
I added the line
and now it's work.
the two function, setParent and setParentItem are necessary, the first is for the item appears on hierarchy of parents and the seconds function to has link on stage to the parent (eg with the change of opacity)
now I have an another problem, this is my qml file
the error is: Unable to assign undefined value
but the image appers on the correct position. I think this error is because the qml don't know who is parent, because the serParent is after the create component.
I can put the id of parent instead of "parent" into qml file but the error is worse
"ReferenceError: Can't find variable: main" mais is id of my main qml and nothing apper.
try using this:
anchors.bottom = parent.bottom
It's work, even with the id everything works.
Could you please add [SOLVED] to thread title?