Ivan Akulov
Ivan Akulov

Reputation: 4323

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?

Upvotes: 6

Views: 7929

Answers (4)

Diederik
Diederik

Reputation: 6488

Generally, I don't like to delete Qt widgets, rather remove them from the appropriate layout. (Qt will delete its own widgets if you set the Delete on close window attribute. ) The difference between calling delete and delete later is that delete is the normal C++ delete operation that will call the destructor and free the memory associated with the object.

The deleteLater() method, as discussed in the Qt documentation deletes the object when the event loop is entered.

Upvotes: 0

SaKabmar_Ashna
SaKabmar_Ashna

Reputation: 144

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

Upvotes: 1

Ivan Akulov
Ivan Akulov

Reputation: 4323

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

by @FrankOsterfeld here.

Upvotes: 3

jdi
jdi

Reputation: 92569

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.

Upvotes: 4

Related Questions