Search code examples
pythonlistpyqtappendqlineedit

How can I append the same element several times in python?


I am creating a GUI with NUMBER of line edits. However, to get the text that is written in them I tried to make a list of LineEdits and append/add a LineEdit element to the list for each iteration. Then I tried to add the current item to the layout and when pushing continue be able to change the NAME_LIST to the rename lineEdits.

I have tried to written out the length of the self.lineEditRename and it seems as the same item cannot be appended several times. Is this right, and how can I get around this? I get this error when I run the file..

layout.addWidget(self.lineEditRename[i],2,i)
IndexError: list index out of range

please help:)

# NAME LIST
self.NAME_LIST = []
for i in range(0, NUMBER):
    self.NAME_LIST.append("NUMBER: "+ str(i))

for i in range(0,NUMBER+1):
            print(i)
            if (i==0):
                layout.addWidget(QtWidgets.QLabel("Rename: "),2,i))
            else:
                layout.addWidget(QtWidgets.QLabel(self.NAME_LIST[i-1]),0,i)
                self.lineEditRename = [QtWidgets.QLineEdit(self), QtWidgets.QLineEdit(self)]
                self.lineEditRename.append(QtWidgets.QLineEdit(self))
                layout.addWidget(self.lineEditRename[i-1],2,i)

self.QContinueButton = QtWidgets.QPushButton("Continue")
self.QContinueButton.clicked.connect(lambda: self.windowtwo(NUMBER))
layout.addWidget(self.QContinueButton,10,2)


def windowtwo(self, NUMBER):
        for i in range(1,NUMBER+1):
            print(self.lineEditRename[i].text())
            self.NAME_LIST[i-1]=self.lineEditRename[i].text()
        self.switch_window.emit()

Solution

  • Your issue is because of this line self.lineEditRename = [QtWidgets.QLineEdit(self), QtWidgets.QLineEdit(self)]. The length of self.lineEditRename will always be 3 so as soon as i becomes 3, you will get a IndexError: list index out of range.

    Did you mean to do this instead:

    self.lineEditRename = [QtWidgets.QLineEdit(self), QtWidgets.QLineEdit(self)]
    for i in range(0,NUMBER+1):
        print(i)
        if (i==0):
            layout.addWidget(QtWidgets.QLabel("Rename: "),2,i))
        else:
            layout.addWidget(QtWidgets.QLabel(self.NAME_LIST[i-1]),0,i)
            self.lineEditRename.append(QtWidgets.QLineEdit(self))
            layout.addWidget(self.lineEditRename[i],2,i)