[Interest] Taking back a widget from a QBoxLayout?

Jason H jhihn at gmx.com
Fri Feb 22 17:45:05 CET 2019

> Sent: Friday, February 22, 2019 at 11:27 AM
> From: "René J.V. Bertin" <rjvbertin at gmail.com>
> To: "interest at qt-project.org Interest" <interest at qt-project.org>
> Subject: [Interest] Taking back a widget from a QBoxLayout?
> Hi,
> Consider
> ```
> SomeWidgetClass *a = maybeReturnSomeWidget();
> SomeOtherQWidgetClass *b = maybeReturnSomeOtherWidget();
> QWidget *combined = new QWidget();
> QVBoxLayout *layout = new QVBoxLayout();
> layout->addWidget(a);
> layout->addWidget(b);
> combined->setLayout(layout);
> if (doWeLikeItCombined) {
>   return combined;
> }
> // get back our widgets
> layout->removeWidget(a);
> layout->removeWidget(b);
> delete combined; // deleteLater()?
> return a ? a : b;
> ```
> The test on the combined widget looks at its size, which apparently I cannot get reliably from a->height(), b->width() and family directly.
> I thus need to take back my widgets a and b from the layout and it seems that what I do currently isn't good enough because the code crashes when after I return something other than the combined widget.
> Is this a catch-22 one can get out of?

I am not 100% sure, it's been a while, but I would assume that the layout is not the true parent, combined is. The "delete combined" will delete child widgets a and b. You need to unparent them, then delete combined. Layouts allocate pixels and resize things, they don't own them, AFAIK.

More information about the Interest mailing list