QT5.4 remove and delete widget in a layout

喜你入骨 提交于 2020-01-17 01:17:50

问题


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.



来源:https://stackoverflow.com/questions/29907695/qt5-4-remove-and-delete-widget-in-a-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!