【问题标题】:Pyqt fails to add layout after removingPyqt 删除后添加布局失败
【发布时间】:2017-08-21 20:46:11
【问题描述】:

我想为 QGroupbox 添加一个布局。通过阅读this answer,我可以毫无问题地添加我想要的元素。在this answer 的帮助下,我又学会了如何移除小部件。所有这一切都很好第一次。当我现在想将具有相同小部件的布局再次添加到我的 QGroupbox 中时,它们不会出现。

但是,它们似乎在那里,因为我的打印调试向我显示,有项目。我知道this question,它显示了如何动态添加小部件,但没有显示如何删除它们。

我的镜头:

def test_class(self): #called by a button 
    self.layout = QGridLayout()
    label1 = QLabel('mylabel1')
    label2 = QLabel('mylabel2')
    combo1 = QComboBox()

    self.layout.addWidget(label1,0,0)
    self.layout.addWidget(label2,1,0)
    self.layout.addWidget(combo1,2,0)
    self.grpbox.setLayout(self.layout) # the Qgroupbox which holds the layout


def clearLayout(self, layout):
    print "called"
    if layout is not None:
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            print item, widget # does print when calling the methods again
            if widget is not None:
                widget.deleteLater()
            else:
                self.clearLayout(item.layout())

def test_remove(self): # called by a button 
    self.clearLayout(self.layout)

如何在第一次添加和删除循环后使我的新布局可见?

【问题讨论】:

    标签: python qt qt4


    【解决方案1】:

    我用一个简单的技巧解决了我的问题。每次我调用变量self.layout时出错,我按下了按钮。通过在我的代码的 init 函数中调用变量,我得到了预期的结果,小部件不仅出现了,而且在它们第一次被删除后可以被召回。

    变化是:

    def __init__(self):
        self.layout = QGridLayout() # created here rather then in the test_class Function 
    
    def test_class(self): #called by a button 
        label1 = QLabel('mylabel1')
        label2 = QLabel('mylabel2')
        combo1 = QComboBox()
    
        self.layout.addWidget(label1,0,0)
        self.layout.addWidget(label2,1,0)
        self.layout.addWidget(combo1,2,0)
        self.grpbox.setLayout(self.layout) # the Qgroupbox which holds the layout
    

    【讨论】:

      猜你喜欢
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 2018-12-26
      • 2022-01-09
      • 2017-09-06
      相关资源
      最近更新 更多