0

I am currently working on a GUI. I work with PyQt5. One widget should appear serval times on the GUI but on diffrent locations. Thats why I would like to creat them in a loop.

This is the code for one single widget:

from PyQt5 import QtCore, QtGui, QtWidgets
_translate = QtCore.QCoreApplication.translate

class Ui_MainWindow(object):
    """ Graphical Simulation Window. """
    def setupUi(self, MainWindow):
        """ Creates the Window. """
        # Basic drawing (not important to understand for this issue):
        MainWindow.setEnabled(True)
        MainWindow.resize(423, 583)
        self.entry_person = QtWidgets.QLabel(MainWindow)
        self.entry_person.setGeometry(QtCore.QRect(85, 510, 30, 30))
        self.entry_person.setAlignment(QtCore.Qt.AlignCenter) #centers the number
        self.entry_person.setStatusTip(_translate("MainWindow", "Waiting Passengers"))
        self.entry_person.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-weight:600;\">1</span></p></body></html>"))
        self.entry_person.setStyleSheet("border: 2px solid  #000000;\n"
"border-radius: 15px;\n"
"background-color: rgb(0, 170, 0);")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Now I need exactly this widget seven times on my GUI. Only diffrence: location and the number at the end of the variable name.

Up until now I tried to do it in a for-loop:

for i in range(7):
    exec("self.entry_person_%s = 'QtWidgets.QLabel(self.centralwidget)'"%i)
    exec("self.entry_person_%s.setGeometry(QtCore.QRect(85, 510, 30, 30))"%i)

But this does not work and its not really what I expected, because its difficult to write the coamnd lines in a string. That causes a lot of errors. May you have a working solution?

Thank you so much for your time and I appreciate your help.

meicf1
  • 25
  • 7
  • 1
    Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – David Buck May 15 '20 at 12:14
  • Thank you so much, after a short rethink I could hanle the situation with dicts. I wouldn't have come to this solution alone. Just for your insight it workt like that: `self.entry_person = {} for i in range(7): self.entry_person[i] = QtWidgets.QLabel(self.centralwidget)` – meicf1 May 16 '20 at 08:08

0 Answers0