pyqt: how to remove a widget?

I have a QGroupBox widget with children in it that I want to remove. How do I do that? I can't find any removeWidget , removeChild , removeItem , or anything similar in the docs. I can only see how to remove things from a layout, but that, apparently, doesn't remove it from the actual widget.


If your widget have no child widgets that depend on it i think you can use:

layout.removeWidget(self.widget_name)
self.widget_name.deleteLater()
self.widget_name = None

in my tests when it is a widget that have childs you have to:

import sip
layout.removeWidget(self.widget_name)
sip.delete(self.widget_name)
self.widget_name = None

if you don't have a variable name for the widget at class or global level you still can remove from layout with layout.takeAt(index) and get the widget pointer from the QLayoutItem this functions returns with QLayoutItem.widget() method, in that case you don't need to assign to None the variable name because it is not referenced outside your function.

Try both methods and see what works for you (don't leak memory after repeat a good bunch of times).


Well, this works: on the widget i want to remove, call widget.setParent(None) . I like how adding to a layout adds a widget to the container, but removing from a layout doesn't... fun stuff.


Are you sure you want to actually delete the widget? Won't hide do? IMHO the accepted method is using show / hide to make widgets appear and disappear from the user's view.

An alternative is using QStackedWidget

链接地址: http://www.djcxy.com/p/77404.html

上一篇: 如何从给定的小部件获得顶级父级?

下一篇: pyqt:如何删除一个小部件?