python - 从布局中删除所有项目

标签 python layout pyqt pyqt4

我试图找到可以采用 qt 布局并从中删除所有内容的东西。想象一下窗口的样子 - 我有:

QVBoxLayout
     | ------QHboxLayout
                 |---------QWidget
     | ------QHboxLayout
                 |---------QWidget
            .........

所以我需要一些我可以递归调用的东西来清除和删除我父 QVBoxLayout 中的所有内容。我试过这里提到的东西(Clear all widgets in a layout in 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'

=>编辑 这有点管用(但如果除了 HBoxLayout 之外还有任何其他 Layout 则不会:

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

最佳答案

清除布局的最安全方法是使用其 takeAt 提取项目方法,然后使用 deleteLater 显式删除任何小部件:

def clearLayout(self, layout):
    if layout is not None:
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else:
                self.clearLayout(item.layout())

关于python - 从布局中删除所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9374063/

相关文章:

android - 为什么我的 android Activity 总是开始滚动到底部?

python - 更新动态 QGridLayout - Python PyQt

python - 如何将图像应用到小部件背景(叠加)

python - 为什么 PyQt 在没有信息的情况下崩溃? (退出代码 0xC0000409)

python - 单击菜单标题时连接功能

python - 值错误: seek of closed file Working on PyPDF2 and getting this error

python - 如何取消最后调用的方法?

python - 为什么我的 Python 脚本比它的 R 脚本慢得多?

Python - 合并许多形状未知的大numpy数组,这些数组不适合内存

html - 根据内容动态调整 css 网格列的高度