for循环只能在python类中运行一次吗?

问题描述:

我想在一个窗口中显示十行'测试'标签,所以我使用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() 

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

非常感谢你! –

问题在于你只能在课堂上创建一个已知的标签。任何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中迭代并逐个修改它们。 您可以做的另一件事是有一个列表,您可以追加每个标签,并可以在以后轻松访问它们。