Search code examples
qtparentparent-childqml

QML Repeater: parent/child vs ownership


can anyone help my clarify what QML Repeater docs mean firstly saying

“Items instantiated by the Repeater are inserted, in order, as children of the Repeater's parent.”,

and then

“Note: A Repeater item owns all items it instantiates. Removing or dynamically destroying an item created by a Repeater results in unpredictable behavior.”?

Aren't child/parent relationship and ownership the same for visual objects in QML?


Solution

  • Object parent (ownership) and visual parent are not the same in QtQuick. The object parent is set at creation time and is never changed. The visual parent can be changed at any time via the 'parent' property.

    The Repeater creates the delegates and sets ownership to itself and the visual parent to its parent. In other words, the Repeater owns the delegates, but leaves the visual presentation to its parent (in most cases, a positioner).

    The Qt 5 documentation is being improved in this area. Here is a snippet (the Qt 5 doc snapshot hasn't been updated recently - this is from the source):

    There are two separate kinds of parenting in a QML application which uses Qt Quick. The first kind is the ownership-parent (also known as the QObject parent) which determines object lifetime semantics. The second kind is the visual-parent which determines where on the canvas an item is drawn, and also certain properties (for example, opacity applies to visual children).

    In almost all cases, the visual-parent is identical to the ownership-parent. See the documentation about the Visual Parentfor more in-depth information on the topic.

    Unfortunately the "Visual Parent" topic hasn't been written yet.