1

I have a QStackedWidget which has a bunch of static "pages" but in a couple of cases one page needs to be recreated when it's switched to. Currently I have something like this:

void InsetNavigator::Navigate(InsetPage *page)
{
    auto current_page = qobject_cast<InsetPage*>(stacked_widget_->currentWidget());
    auto current_idx = stacked_widget_->currentIndex();
    current_page->MadeHidden();
    stacked_widget_->removeWidget(current_page);
    current_page->setParent(nullptr);
    delete current_page;
    stacked_widget_->insertWidget(current_idx -1, page);
    stacked_widget_->setCurrentWidget(page);
    page->MadeVisible();
}

My question is, do I need to bother with reparenting the current page to a nullptr before deleting it, or can I just delete the current_page and the QStackedWidget will handle the fact that it's been deleted for me? I don't know if leaving the stacked widget as the parent but deleting the pointer will cause issues.

gfree
  • 479
  • 7
  • 16
  • 1
    You have to call `removeWidget` and `delete currentPage` but you avoid to call `setParent` – Marco Beninca Aug 26 '22 at 15:27
  • 3
    ***Do I need to setParent to nullptr before deleting QWidget that's owned by QStackedWidget*** No, never. The destructor of QObject will notify the parent. – drescherjm Aug 26 '22 at 15:30
  • 1
    I did not post an answer because I expect there is a duplicate. Also I was hoping to find this information in the documentation but I did not. – drescherjm Aug 26 '22 at 15:33
  • 1
    there's a lot of stuff I hope to find in the documentation, but alas it's not :). I found similar sorts of questions but nothing explicitly stating what you just mentioned. – gfree Aug 26 '22 at 15:42
  • Isn't it a duplicate of https://stackoverflow.com/questions/26817169/qt-qwidget-removal-and-deletion-setparentnull-necessary ? The only difference I can see is that the previous question is more general. There's also a quote from [the docs](https://doc.qt.io/qt-6/objecttrees.html): "You can also delete child objects yourself, and they will remove themselves from their parents," thus if there's any issue with _just delete_ -- file a bug! – absolute.madness Aug 27 '22 at 23:20

1 Answers1

0

It depends on how the container-widget is implemented.

But in most-cases if not all, the container-widget (QStackedWidget in OP's case) updates own internal-state automatically once any child-widget is deleted.

Top-Master
  • 7,611
  • 5
  • 39
  • 71