I am trying to create labels and textboxes dynamically in PyQt5 however, i have no idea how i can read data entered in the textboxes when a user hits the save button. My code looks as follows:
self.setWindowTitle("Yaml --> Json")
self.setGeometry(self.left, self.top, self.width, self.height)
self.createLayout()
vbox = QVBoxLayout()
for i in range(0, len(self.listItems)):
vbox.addWidget(QLabel(list(self.listItems.keys())[i]))
vbox.addWidget(QLineEdit())
vbox.addWidget(self.groupBox)
self.setLayout(vbox)
self.show()
def createLayout(self):
self.groupBox = QGroupBox()
hboxLayout = QHBoxLayout()
button = QPushButton("Save", self)
button.setIcon(QtGui.QIcon("save.png"))
button.setIconSize(QtCore.QSize(40, 40))
button.setMinimumHeight(40)
button.clicked.connect(self.ClickSave)
hboxLayout.addWidget(button)
button1 = QPushButton("Exit", self)
button1.setIcon(QtGui.QIcon("exit.png"))
button1.setIconSize(QtCore.QSize(40, 40))
button1.setMinimumHeight(40)
button1.clicked.connect(self.ClickExit)
hboxLayout.addWidget(button1)
self.groupBox.setLayout(hboxLayout)
def ClickExit(self):
print("Exited!!")
sys.exit()
def ClickSave(self):
print("Saved!")```
You could just assign the widgets you want to access later to instance variables or store them in a list, e.g.
self.line_edit_list = []
for i in range(0, len(self.listItems)):
vbox.addWidget(QLabel(list(self.listItems.keys())[i]))
line_edit = QLineEdit()
vbox.addWidget(line_edit)
self.line_edit_list.append(line_edit)
....
def ClickSave(self):
for edit in self.line_edit_list:
print(edit.text())