2017-10-05 114 views
-1

我想在一個窗口中顯示十行'測試'標籤,所以我使用for循環,但它只顯示一行。
我想我的代碼中的for循環放錯了位置,但我不知道如何使其正確。for循環只能在python類中運行一次嗎?

下面是主要代碼:

class Home(QMainWindow): 
    def __init__(self, parent = None): 
     super(Home, self).__init__(parent) 
     self.setGeometry(300,100,400,300) 
     self.scrollLayout = QFormLayout() 

     self.scrollWidget = QWidget() 
     self.scrollWidget.setLayout(self.scrollLayout) 

     self.scrollArea = QScrollArea() 
     self.scrollArea.setWidgetResizable(True) 
     self.scrollArea.setWidget(self.scrollWidget) 

     self.mainLayout = QVBoxLayout() 
     self.mainLayout.addWidget(self.scrollArea) 

     self.centralWidget = QWidget() 
     self.centralWidget.setLayout(self.mainLayout) 
     self.setCentralWidget(self.centralWidget) 

     self.Lbl = QLabel('test') 
     for i in range(20):### here, it only loops 1 time 
      self.scrollLayout.addRow(self.Lbl) 

     self.show() 

回答

0

1  self.Lbl = QLabel('test') 
2  for i in range(20):### here, it only loops 1 time 
3   self.scrollLayout.addRow(self.Lbl) 

你需要把1號線居然在for循環(線2 ... 3號線)

+0

非常感謝你! –

0

問題在於你只能在課堂上創建一個已知的標籤。任何Widget類型(QLabel)只能添加一次到任何「容器」。因此,當您在其他地方添加標籤或在同一位置添加標籤時,您將添加相同的標籤20次,並將其添加到新位置,但一個標籤不能同時位於兩個位置。


這裏是東西,你必須創建一個新的標籤,每個迴路,所以你將有類似的東西:

for i in range(20): 
    lbl = QLabel("teste"+str(i)) # here you are creating one new label to each loop 
    self.scrollLayout.addRow(lbl) 

但要記住,這樣,現在你沒有一個實例保存在每個標籤的變量中,要訪問每個標籤,您必須在scrollLayout中迭代並逐個修改它們。 您可以做的另一件事是有一個列表,您可以追加每個標籤,並可以在以後輕鬆訪問它們。