清除pyqt中布局中的所有小部件 [英] Clear all widgets in a layout in pyqt

查看:97
本文介绍了清除pyqt中布局中的所有小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法清除(删除)布局中的所有小部件?

Is there a way to clear (delete) all the widgets in a layout?

self.plot_layout = QtGui.QGridLayout()
self.plot_layout.setGeometry(QtCore.QRect(200,200,200,200))
self.root_layout.addLayout(self.plot_layout)
self.plot_layout.addWidget(MyWidget())

现在我想用一个新的小部件替换 plot_layout 中的小部件.是否有一种简单的方法可以清除 plot_layout 中的所有小部件?我没有看到任何这样的方法.

Now I want to replace the widget in plot_layout with a new widget. Is there an easy way to clear all the widgets in plot_layout? I don't see any method such.

推荐答案

经过大量研究(这个研究花了很多时间,所以我在这里添加以供将来参考),这是我发现真正清晰和删除布局中的小部件:

After a lot of research (and this one took quite time, so I add it here for future reference), this is the way I found to really clear and delete the widgets in a layout:

for i in reversed(range(layout.count())): 
    layout.itemAt(i).widget().setParent(None)

文档对 QWidget 的说明那是:

What the documentation says about the QWidget is that:

新小部件在其父级被删除时也被删除.

The new widget is deleted when its parent is deleted.

重要说明:您需要向后循环,因为从开头删除内容会移动项目并更改布局中项目的顺序.

Important note: You need to loop backwards because removing things from the beginning shifts items and changes the order of items in the layout.

测试并确认布局为空:

for i in range(layout.count()): print i

<小时>

似乎有另一种方法可以做到.不要使用 setParent 函数,而是使用 deleteLater() 函数,如下所示:

for i in reversed(range(layout.count())): 
    layout.itemAt(i).widget().deleteLater()

文档说QObject.deleteLater (self)

计划删除该对象.

但是,如果您运行上面指定的测试代码,它会打印一些值.这表明布局仍然有项目,而不是带有 setParent 的代码.

However, if you run the test code specified above, it prints some values. This indicates that the layout still has items, as opposed to the code with setParent.

这篇关于清除pyqt中布局中的所有小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆