Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 339
Claudiu Avatar asked May 05 '11 14:05

Claudiu


People also ask

How do I remove a widget in Python?

We can delete widgets from the window or frame using the . destroy method in tkinter. It can be invoked in the widget by defining a function for it.

How do I remove a widget?

Just touch and hold the widget you want to remove, and then tap Remove from Home.

How do I delete a widget data?

Tap and hold the widget you want to remove. A small menu pops up next to it. Locate the Remove button in this menu and tap on it. That's it!

What is a widget in PYQT?

Widgets are the basic building blocks for graphical user interface (GUI) applications built with Qt. Each GUI component (e.g. buttons, labels, text editors) is a widget that is placed somewhere within a user interface window, or is displayed as an independent window.


2 Answers

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).

like image 68
skuda Avatar answered Oct 19 '22 13:10

skuda


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.

like image 42
Claudiu Avatar answered Oct 19 '22 13:10

Claudiu