在文本文件python中复制/保存PyQt5 Listbox项

时间:2017-06-12 05:35:41

标签: python-3.x pyqt5 listboxitems

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

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(自我)下的代码:不起作用。

1 个答案:

答案 0 :(得分:1)

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)