Search code examples
pythonpyqtpyqt4qlabel

Create and Updating Multiple QLabel in PYQT4


How can I create a number of (say 56) labels within a widget in a loop?

Say I have a list called column:

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

What I did is:

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)

For each element in the list, there would be a corresponding blank QLabel. All blank Qlabes would be updated simultaneously by clicking the check button using the setText function.

brief view of the UI

I know this method is not right as I am not supposed to use the string as variable names, and I am having a problem updating infor_labels(the blank labels) since I can't actually call them.

Can anyone please kindly provide suggestions? Additional explanation or information will be given if the above description confuses.


Solution

  • You can use setattr() to create variables dynamically using a string as shown below:

    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_())