0

I am creating a basic GUI application which implements D'hontds method using PyQt5, and having trouble creating Qlbales dynamically i.e. I want to display the results in these labels, and the number of labels is based on the number of inputs by the user so it varies. I could create the maximum number and then use just the ones I need, but I am sure there are neater and more effective solutions.

I have tried with exec and eval (I know it is poor approach), but nevertheless I have not succeeded. I think eval fails to read element from the list somehow, not sure. Here is what I've tried (i+5 because I have 4 more labels) :

def set_result_labels(self):

        font = QtGui.QFont()
        font.setPointSize(15)
        for i in range(len(self.text_parties_names)):
            exec(f"self.label_{i+5} = QtWidgets.QLabel(self.centralwidget)")
            eval(f"self.label_{i+5}.setGeometry(QtCore.QRect(640, {(i+5)*40}, 50, 50))")
            eval(f"self.label_{i+5}.setFont(font)")
            eval(f"self.label_{i+5}.setText(self.text_parties_names[i])") 

and self.text_partirs_names is list with the names from textEdits (user input):

def get_parties_names(self):
        for text_edit in self.text_edit_parties_list:
            if text_edit.toPlainText():
                self.text_parties_names.append(text_edit.toPlainText())
kaktus_car
  • 986
  • 2
  • 11
  • 19
  • 1
    don't use eval or exec, instead use setattr: `label = QtWidgets.QLabel(self.centralwidget) label.setGeometry(QtCore.QRect(640, (i+5)*40, 50, 50)) ... setattr(self, f"label_{i+5}", label)` – eyllanesc May 30 '20 at 23:26
  • Yeah, this is exactly what I was looking for. Thank you – kaktus_car May 30 '20 at 23:31

0 Answers0