问题
I have a QStackedLayout which contains few QWidget on it. The widgets layout is QVBoxLayout which have also few QPushButton. What I wanted to do is to remove all the widgets inside the QStackedLayout and then delete the widgets and layouts BUT I want all the buttons not to be deleted 'cause I will put them to another widget later.
Here's my code:
while (QLayoutItem *item = m_stacked_layout->takeAt(0)) {
QWidget *w = item->widget();
for (int i = 0; i < w->layout()->count(); i++) {
QPushButton *button = qobject_cast<QPushButton *>(w->layout()->itemAt(i)->widget());
if (button) {
w->layout()->removeWidget(button);
}
}
delete w;
delete item;
}
The application crashes at the line delete w;. And, if I remove the delete lines, application works fine.
回答1:
BUT I want all the buttons not to be deleted 'cause I will put them to another widget later.
- Hide all widgets that you want to transfer
- Set parent widget for all this widgets to
nullptr - Later... set necessary parent and show widgets
Note: if you want to delete widgets inside some slots, you should use deleteLater method.
来源:https://stackoverflow.com/questions/29907695/qt5-4-remove-and-delete-widget-in-a-layout