Copy/Save 文本文件中的 PyQt5 列表框项目 python

Copy/Save PyQt5 Listbox items in a text file python

在多次点击“添加”按钮后,它会将项目添加到列表框中。我希望使用保存按钮将列表框中的所有项目保存到文本文件中。

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_())

但是 def SAVE(self): 下的代码不起作用。

self.listView 是一个对象,不能被 self.listView() 调用。我想你想保存项目的文本。您可以从 listViews 模型中获取它和项目的所有其他数据:

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)

或询问 text() 项:

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)