QT5.4 remove and delete widget in a layout

2019-09-11 00:36发布

问题:

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.

  1. Hide all widgets that you want to transfer
  2. Set parent widget for all this widgets to nullptr
  3. Later... set necessary parent and show widgets

Note: if you want to delete widgets inside some slots, you should use deleteLater method.