我该如何清理QFormLayout?

时间:2015-10-02 19:20:20

标签: python layout pyside

我想动态更改QFormLayout内容。我可以使用布局takeAt()方法。 但是rowCount()保留了它的编号,每次重建表格时,它都会返回越来越多的数字......

如果布局项目干净,如何让rowCount返回0

# coding: utf-8
import sys, os

from PySide.QtGui import *

class TestWindow(QWidget):
    def __init__(self):
        super(TestWindow, self).__init__()

        self.formArea = QWidget(self)
        self.formlayout = QFormLayout()
        self.formArea.setLayout(self.formlayout)

        rebuildButton = QPushButton(self)
        rebuildButton.setText('Rebuild')
        rebuildButton.clicked.connect(self.rebuildForm)

        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.addWidget(self.formArea)
        layout.addWidget(rebuildButton)

        self.rebuildForm()

    def rebuildForm(self):
        # clear all items in formlayout
        print('##### start cleaning #####')
        while self.formlayout.count() :
            print('current count = %d / rowCount = %d' % (self.formlayout.count(),
                                                          self.formlayout.rowCount()))
            item = self.formlayout.takeAt(0)
            del(item)

        # build forms
        for i in xrange(3) :
            lineEdit = QLineEdit(self.formArea)
            self.formlayout.addRow('row %d' % i, lineEdit)

if __name__ == '__main__' :
    app = QApplication(sys.argv)
    win = TestWindow()
    win.show()
    app.exec_()

这是它的输出,推动呼叫rebuildForm 3次。

##### start cleaning #####
##### start cleaning #####
current count = 6 / rowCount = 3
current count = 5 / rowCount = 3
current count = 4 / rowCount = 3
current count = 3 / rowCount = 3
current count = 2 / rowCount = 3
current count = 1 / rowCount = 3
##### start cleaning #####
current count = 6 / rowCount = 6
current count = 5 / rowCount = 6
current count = 4 / rowCount = 6
current count = 3 / rowCount = 6
current count = 2 / rowCount = 6
current count = 1 / rowCount = 6
##### start cleaning #####
current count = 6 / rowCount = 9
current count = 5 / rowCount = 9
current count = 4 / rowCount = 9
current count = 3 / rowCount = 9
current count = 2 / rowCount = 9
current count = 1 / rowCount = 9

1 个答案:

答案 0 :(得分:0)

你做不到。这是一些布局的实现细节(QGridLayout是另一种布局),逻辑行的数量永远不会减少。这就是没有removeRow()方法的原因。因此,不要尝试删除所有行,只需重新使用已存在的行(并在必要时添加更多行)。

您也可以忽略空行,并使用getWidgetPosition之类的方法,这样您就可以使用逻辑行,而不是 visual