2015-10-02 61 views
1

我想動態更改QFormLayout內容。我可以使用佈局的takeAt()方法。 但是,rowCount()正在舉行的號碼,我每次重建形式時,會返回越來越多......我如何清理QFormLayout?

我怎樣才能讓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 

回答

0

你不能。這是一些佈局的實現細節(QGridLayout是另一種),邏輯行的數量從不減少。這就是爲什麼沒有removeRow()方法。因此,不要試圖刪除所有的行,而是重新使用那些已經存在的行(並在必要時添加更多行)。

你也可以忽略空行和使用方法,如getWidgetPosition,讓您始終與邏輯行工作,而不是視覺行。