python-3.xpyqt5listboxitems

Copy/Save PyQt5 Listbox items in a text file python


After several clicks of Add button, it adds items to the listbox. I wish to save all the items from the listbox to a textfile with the save button.

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 300)
        self.listView = QtWidgets.QListWidget(Dialog)
        self.listView.setGeometry(QtCore.QRect(120, 40, 256, 192))
        self.listView.setObjectName("listView")
        self.AddButton = QtWidgets.QPushButton(Dialog)
        self.AddButton.setGeometry(QtCore.QRect(20, 80, 75, 41))
        self.AddButton.setObjectName("AddButton")
        self.SaveButton = QtWidgets.QPushButton(Dialog)
        self.SaveButton.setGeometry(QtCore.QRect(20, 140, 75, 41))
        self.SaveButton.setObjectName("SaveButton")

        self.AddButton.clicked.connect(self.ADD)
        self.SaveButton.clicked.connect(self.SAVE)


        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.AddButton.setText(_translate("Dialog", "Add to List"))
        self.SaveButton.setText(_translate("Dialog", "Save"))


    def ADD(self):
        self.listView.addItem("SAMPLE STRING")

    def SAVE(self):
        s = open('textfile.txt','a')
        for items in self.listView():
            s.write(item)
        s.close()


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

but the code under the def SAVE(self): doesn't work.


Solution

  • self.listView is an object and not callable by self.listView(). I suppose you want to save the items's text. You can get it and all other data of the items from the listViews model:

    def SAVE(self):
        with open('textfile.txt','a') as s:
            for i in range(self.listView.model().rowCount()):
                text = self.listView.model().data(self.listView.model().index(i))
                # print(i, text)
                s.write(text)
    

    or ask for the text() of the items:

    def SAVE(self):
        with open('textfile.txt','a') as s:
            for i in range(self.listView.model().rowCount()):
                text = self.listView.item(i).text()
                # print(i, text)
                s.write(text)