从布局中删除所有项目 [英] Remove all items from a layout

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

问题描述

我正试图找到一种采用qt布局并从中删除所有内容的东西.只是想像一下窗口是什么样子-我有:

I was trying to find something that would take a qt layout and delete everything from it. Just to imagine what the window looks like - I have:

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

因此,我需要我可以递归调用的东西,以清除并删除父母QVBoxLayout中的所有内容.我尝试了此处提到的内容(清除pyqt中布局中的所有小部件),但它们都不起作用(无论如何都没有标记正确答案).我的代码如下:

So I need something that I can call recursively to CLEAR AND DELETE all the stuff from my parent QVBoxLayout. I tried things mentioned here (Clear all widgets in a layout in pyqt) but none of them work (no correct answer marked anyway). My code looks like this:

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

但是它给出了一个错误:

But it gives an error:

               layout.itemAt(i).widget().close()
            AttributeError: 'NoneType' object has no attribute 'close'

=>编辑 这种方法有效(但如果Layout以外的Layout则没有其他作用:

=>EDIT This kinda works (but doesn't if there is any other Layout than 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()

推荐答案

清除布局的最安全方法是使用

The safest way to clear a layout is to extract the items with its takeAt method, and then explicitly delete any widgets with 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())

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

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