在 PYQT4 中创建和更新多个 QLabel

Create and Updating Multiple QLabel in PYQT4

如何在循环中的小部件内创建多个(比如 56 个)标签?

假设我有一个名为列的列表:

column = ['a','b','c','d',.......'y','z']

我做的是:

class ApplicationWindow_1(QWidget):

  def __init__(self,parent = None):
      super(ApplicationWindow_1,self).__init__(parent)
      self.resize(400,900)

        for i in range(len(column)):
          column_name =  str(column[i]) + '_label_name'
          self.column_name = QLabel(column[i],self)
          self.column_name.resize(120,30)
          self.column_name.move(30,100+(i-1)*20)

          infor_name = str(column[i]) + '_label_infor'
          self.infor_name = QLabel(self)
          self.infor_name.resize(120,30)
          self.infor_name.move(230,100+(i-1)*20)

对于列表中的每个元素,都会有一个对应的空白 QLabel。通过使用 setText 函数单击复选按钮,所有空白 Qlabes 将同时更新。

UI

的简要介绍

我知道这个方法不对,因为我不应该使用字符串作为变量名,而且我在更新 infor_labels(空白标签)时遇到了问题,因为我实际上无法调用它们.

有哪位好心人可以给点建议吗?以上描述如有混淆之处,另行说明或补充。

您可以使用 setattr() 使用字符串动态创建变量,如下所示:

from PyQt4 import QtCore, QtGui


class ApplicationWindow_1(QtGui.QWidget):
    def __init__(self,parent = None):
        super(ApplicationWindow_1,self).__init__(parent)
        flay = QtGui.QFormLayout(self)

        texts = ["name", "address", "phone"]

        for text in texts:
            label_1 = QtGui.QLabel(text+": ")
            label_1.setFixedSize(120, 30)
            label_2 = QtGui.QLabel()
            label_2.setFixedSize(120, 30)
            flay.addRow(label_1, label_2)

            # An attribute of the class is created with setattr()
            setattr(self, "{}_infor_label".format(text), label_2)

        # use
        self.name_infor_label.setText("some name")
        self.address_infor_label.setText("some address")
        self.phone_infor_label.setText("some phone")


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    w = ApplicationWindow_1()
    w.show()
    sys.exit(app.exec_())