我想找一个可以删除qt布局中所有内容的工具。就像你可以想象出窗口长什么样子一样 - 我有:
QVBoxLayout
| ------QHboxLayout
|---------QWidget
| ------QHboxLayout
|---------QWidget
.........
所以我需要一个可以递归调用的东西,来清除并删除我父容器QVBoxLayout
中的所有内容。我尝试了这里提到的东西(在PyQt中清除布局中的所有小部件),但它们都不起作用(无正确答案标记)。我的代码看起来像这样:
def clearLayout(self, layout):
for i in range(layout.count()):
if (type(layout.itemAt(i)) == QtGui.QHBoxLayout):
print "layout " + str(layout.itemAt(i))
self.clearLayout(layout.itemAt(i))
else:
print "widget" + str(layout.itemAt(i))
layout.itemAt(i).widget().close()
但是它会出现错误:
layout.itemAt(i).widget().close()
AttributeError: 'NoneType' object has no attribute 'close'
=>编辑
这个有点起作用(但是如果有任何其他的Layout
而不是HBoxLayout
,则无法起作用):
def clearLayout(self, layout):
layouts = []
for i in range(layout.count()):
if (type(layout.itemAt(i)) == QtGui.QHBoxLayout):
print "layout " + str(layout.itemAt(i))
self.clearLayout(layout.itemAt(i))
layouts.append(layout.itemAt(i))
else:
print "widget" + str(layout.itemAt(i))
if (type(layout.itemAt(i)) == QtGui.QWidgetItem):
layout.itemAt(i).widget().close()
self
是什么并不是很重要。OP的代码使用了一个类的方法,所以我的答案也是用了这个。它同样可以是没有self
的函数。 - ekhumoro