[Interest] Taking back a widget from a QBoxLayout?
giuseppe.dangelo at kdab.com
Fri Feb 22 22:29:03 CET 2019
Il 22/02/19 20:42, Jason H ha scritto:
> When you use a layout, you do not need to pass a parent when constructing the child widgets. The layout will automatically reparent the widgets (using QWidget::setParent()) so that they are children of the widget on which the layout is installed.
> Note: Widgets in a layout are children of the widget on which the layout is installed, not of the layout itself. Widgets can only have other widgets as parent, not layouts.
This is the bulk of the story, and ultimately, what's interesting for you.
> void QLayout::addItem(QLayoutItem *item)
> Implemented in subclasses to add an item. How it is added is specific to each subclass.
> This function is not usually called in application code. To add a widget to a layout, use the addWidget() function; to add a child layout, use the addLayout() function provided by the relevant QLayout subclass.
> Note: The ownership of item is transferred to the layout, and it's the layout's responsibility to delete it.
> void QLayout::addWidget(QWidget *w)
> Adds widget w to this layout in a manner specific to the layout. This function uses addItem().
> So the docs are clear as mud.
The docs are indeed unclear, but look at what you're quoting -- a
function to add QLayoutItems to a layout. A QWidget is NOT a QLayoutItem
(but it is possibly managed by one). QLayout::addItem will add a
QLayoutItem to a layout, passing ownership of the _item_ to the layout
(but not of the widget the layout item is managing).
In other words, if you have a toplevel widget with two children (A and
B), managed by a layout, what you're going to build looks like this from
an ownership point of view:
* QWidget (top)
+—— QWidget A
+—— QWidget B
+-- QWidgetItem (managing A)
\-- QWidgetItem (managing B)
Solid lines represent ownership via QObject parent/child. Dashed lines
represent ownership via other means.
> QLayout mentions "ownership" but the tips mention "parent". FWIW, I knew QWidgets parented QWidgets, but I don't know what it means by "ownership".
They refer to the same thing.
A parent QObject owns (... has ownership of) its children QObjects,
meaning that deleting the parent will deleting the children as well.
Some object Foo acquiring ownership of Bar means that deleting Foo will
also delete Bar. This can happen through QObject parent/child, or some
Giuseppe D'Angelo | giuseppe.dangelo at kdab.com | Senior Software Engineer
KDAB (France) S.A.S., a KDAB Group company
Tel. France +33 (0)4 90 84 08 53, http://www.kdab.com
KDAB - The Qt, C++ and OpenGL Experts
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 4007 bytes
Desc: Firma crittografica S/MIME
More information about the Interest