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());
    _view->scene()->addItem(item);
    item->setParentItem(qobject_cast<QDeclarativeItem*>(_view->rootObject()));
    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
    @if( _view->rootObject()->findChild<QDeclarativeView*>("image1"))@

    _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
    @
    Image {
    id:image1
    objectName:"image1"
    }
    @

    in yor image.qml file and everything should work as expected.
    You should also add:
    @
    item->setParent(_view->rootObject());
    @
    to your code ( http://doc.qt.digia.com/qt/qdeclarativeengine.html#ObjectOwnership-enum )



  • I added the line
    @item->setParent(_view->rootObject());@
    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
    @Image {
    id: image3
    objectName: "image1"
    width: 150
    height: 150
    anchors.bottom: parent.bottom
    source: "5.png"
    }@

    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:
    @
    Image {
    id: image3
    objectName: "image1"
    width: 150
    height: 150

    onParentChanged: {
    if(parent) {
    anchors.bottom = parent.bottom
    }
    }
    source: "5.png"
    }
    @



  • It's work, even with the id everything works.
    Thanks



  • Could you please add [SOLVED] to thread title?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.