Removing a widget that is in the layout

What happens if we run delete widget for the widget that is in the layout? If this case was written in the documentation, please tell me the link (I did not find it).

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 happen differ for l1 and l2 ?

+4
source share
4 answers

I believe that you are doing almost the same thing, although not one of them will correctly remove from the layout how you should do it. They still remain bad links in the layout (if I remember correctly)

The first item simply deletes the item. The second will delete it as soon as the control returns to the event loop. But in fact, the way people usually remove elements from the layout is to take them from the layout (giving it the opportunity to customize it), and then remove the element and its widget (if you want).

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

Again, removing the widget ( child->widget() ) is only necessary if you want to destroy the added widget in addition to the layout element that held it.

+3
source

QLayout listen for events like ChildRemoved and delete items accordingly. Simple widget removal is safe.

@FrankOsterfeld is here .

+3
source

Do not use delete l1 in Qobjects, which has active slots connected to them, you will encounter a failure. Usage: L1-> hide (); L1-> deleteLater (); This works great for me.

+1
source

As a rule, I do not like to remove Qt widgets, but to remove them from the corresponding layout. (Qt will remove its own widgets if you set the Delete attribute to the closing window . The difference between calling delete and delete later is that delete is a normal delete operation that will call the destructor and free up memory associated with the object.

The deleteLater() method, as described in the Qt documentation , deletes the object when you enter the event loop.

0
source

All Articles