Build many QLabel and many QLineEdite with a loop cycle

Viewed 37

I have to build 40 Qlabels with related QLineEdits. In order not to write label_n and line_n where n = number many times I use this code For labels it works correctly because the text is inserted (sold.setText ("aa" + str (i))) but I cannot use it for QLineEdit because it doesn't return any value in value.

class New_Gest(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)

    def setupUi(self, MainWindow):


        MainWindow.setObjectName("MainWindow")
        MainWindow.setGeometry(QtCore.QRect(30, 100, 50, 300))
        MainWindow.setWindowTitle("Aggiornamento Titoli")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        x = 10
        y = 10
        x1 = 40
        y1 = 10
        for i in range(10):
            sold = QtWidgets.QLineEdit(self.centralwidget)
            sold.setGeometry(QtCore.QRect(x, y, x1, y1))
            name = "Clabel{}".format(i+1)
            sold.setObjectName(name)
            sold.setText("aa" + str(i))
            y = y + 20
        for i in range(10):
            obj = self.findChild(QtWidgets.QLineEdit,"Clabel{}".format(i+1))
            value = obj.text()
            print(value)
        MainWindow.setCentralWidget(self.centralwidget)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.show()


def main():
    app = QApplication(sys.argv)
    window = New_Gest()
    window.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

The ideal would be, for me, to have label_n = QtWidgets.QLabel (self.centralwidget) and line_n = QtWidgets.QLineEdit (self.centralwidget),but I do not know how I can do it

1 Answers

Consider this short example

import sys
from PyQt5.QtWidgets import QApplication, QLineEdit, QGroupBox, QVBoxLayout

UI = QApplication(sys.argv)
        
groupbox = QGroupBox()
groupbox.show()
vbox = QVBoxLayout()
edits = []
for i in range(20):
    edits.append(QLineEdit(str(i)))
    vbox.addWidget(edits[-1])
groupbox.setLayout(vbox)

# To retrieve the values:
for i in range(20):
    print(edits[i].text())

UI.exec()

QLineEdits are kept in a list, and are added to a vertical box layout QVBoxLayout. A group box is set to use this layout, and so we get all the QLineEdits vertically on the window.

In most cases, these objects should be stored in a class, in which case you would have something like

class mainwindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()
        
    def init_ui(self):
        self.show()
        self.q_line_edits = []
Related