Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting widget that is in layout

What will happen if we will run delete widget for widget that is in layout? If this case was written in documentation, please give me the link (I didn't find).

Code example:

QLabel *l1 = new QLabel("1st");
QLabel *l2 = new QLabel("2nd");
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(l1);
layout->addWidget(l2);

QWidget *mainWidget = new QWidget;
mainWidget->setLayout(layout);
mainWidget->show();

delete l1;
l2->deleteLater();

Can things that will happen be different for l1 and l2?

like image 355
Ivan Akulov Avatar asked Aug 18 '12 15:08

Ivan Akulov


3 Answers

I believe what you are doing is almost same, though neither would properly remove from layout the way you should be doing it. They are still being left as bad references in the layout (if I remember correctly)

The first one simply deletes the item now. The second will delete it once the control returns back to the event loop. But really, the way people usually remove items from a layout is to take them from the layout (giving it a chance to adjust itself), then delete the item and its widget (if you want).

QLayoutItem *child;
while ((child = layout->takeAt(0)) != 0) {
    delete child->widget();
    delete child;
}

Again, the deleting of the widget (child->widget()) is only needed if you want to destroy the widget that was added, in addition to the layout item that was holding it.

like image 137
jdi Avatar answered Nov 16 '22 20:11

jdi


QLayout's listen for events of type ChildRemoved and remove the items accordingly. Simply deleting the widget is safe.

by @FrankOsterfeld here.

like image 40
Ivan Akulov Avatar answered Nov 16 '22 22:11

Ivan Akulov


dont use delete l1 on Qobjects that has active slots connected to them, you will run into a crash. Use: l1->hide(); l1->deleteLater(); It works fine for me

like image 1
SaKabmar_Ashna Avatar answered Nov 16 '22 22:11

SaKabmar_Ashna