8

i created one QWidget(Parent). in the inside of the parent widget i created another one QWidget(Child). In the run time i need to remove the child widget. how to do that?

i am not using any layout. i am directly putting in the Parent Widget.

Please Help me to fix this.

saravanan
  • 1,605
  • 6
  • 20
  • 25
  • i found the answer: http://stackoverflow.com/questions/3940409/how-to-clear-all-the-widgets-in-parent-widgets – saravanan Oct 15 '10 at 10:54

2 Answers2

8

If you add the widget with e.g.:

QWidget *w = new QWidget(parent);

...then you can remove it with:

delete w;

Another approach would be to just hide it:

w->hide();
sje397
  • 41,293
  • 8
  • 87
  • 103
  • but i don't know the name of the child widget (in run time also i am creating child widget). how to i find and delete it?, – saravanan Oct 15 '10 at 06:26
  • const QObjectList & children () const. It's a QObject's method. You can use to get the children. Or you can simply store a pointer to your widget (which one you want to delete) – Andrew Oct 19 '10 at 13:37
7

This answer is for those arriving from search engines and want an answer to the question as stated in the title.

If you want to remove a child from a parent without deleting it or hiding it (which does NOT remove it from its parent), set the child's parent to NULL.

QWidget::setParent(NULL)

Note that explicitly reparenting a widget like this carries several implications (e.g visibility automatically set to hidden). See QWidgets documentation for more information.

Tenders McChiken
  • 1,216
  • 13
  • 21
  • 3
    After 2 hours of google-fu I found this gem, that really removes (but doesn't delete) a widget from a layout. Now `this->ui->myLayout->removeWidget(myWidget);` is obsolete, too. Thanks for making me continue my web-dev-escapist Qt-app. – JackLeEmmerdeur Aug 24 '20 at 19:33
  • 1
    You sir are a hero. I searched far and wide before finding this answer. THANK YOU! – Malachi Nov 01 '22 at 23:06