6

QML introduces a separate ownership (QObject) tree from the visual tree (QtQuick scene graph).

  • parent returns the visual parent.
  • children returns the visual children.
  • data returns the QObject children.

But how do I access the QObject parent?

FYI, I intend on dynamically creating and destroying nested layouts containing a custom type, so I need to manage the QObject tree - just using the visual tree will result in the 'wrong' objects disappearing after reparenting and then deleting.

László Papp
  • 51,870
  • 39
  • 111
  • 135
cmannett85
  • 21,725
  • 8
  • 76
  • 119

2 Answers2

2

If you don't actually know the parent of the item, I don't think you can find out without going into C++. If you just want to change the item's QObject parent, you should be able to do so in QML by adding it to the data property of its new parent. (This will also change its visual parent, if applicable.)

Quoting the the Qt Quick Concepts documentation:

Any object assigned to an item's data property becomes a child of the item within its QObject hierarchy, for memory management purposes. Additionally, if an object added to the data property is of the Item type, it is also assigned to the Item::children property and becomes a child of the item within the visual scene hierarchy. (Most Qt Quick hierarchy crawling algorithms, especially the rendering algorithms, only consider the visual parent hierarchy.)

bks
  • 1,360
  • 6
  • 7
0

You can avoid unwanted ownership of objects by previous parents by creating them like this:

const someObject = someComponent.createObject( null, { parent: someItem });

This way someItem is only visual parent of someObject. You can move the child elsewhere then delete the container.

really
  • 93
  • 7