简体   繁体   English

PyQt4:保存一个QListWidget

[英]PyQt4: Save a QListWidget

I'm new in PyQt4. 我是PyQt4的新手。

I have a QListWidget, and then i would like to saveit directly but the only example i find is aa textedit and need to open a file first. 我有一个QListWidget,然后我想直接保存它,但是我发现的唯一示例是一个textedit,需要首先打开一个文件。

But in my case there is no file to open. 但就我而言,没有文件可打开。 is it possible to do it? 有可能做到吗?

so far my code looks like this: 到目前为止,我的代码如下所示:

def initUI(self):

    self.edit = QtGui.QListWidget()

    btn1 = QtGui.QPushButton("Check")

    btn2 = QtGui.QPushButton("Quit")

    btn1.clicked.connect(self.buttonClicked)            
    btn2.clicked.connect(self.closeEvent)

    toolBar = QtGui.QToolBar()

    fileButton = QtGui.QToolButton()
    fileButton.setText('File')
    fileButton.setMenu(self.menu())

    saveButton = QtGui.QToolButton()
    saveButton .setText('save')
    saveButton .clicked.connect(self.save_menu)

    toolBar.addWidget(fileButton)
    toolBar.addWidget(saveButton )

def save_menu(self):
    fn = QtGui.QFileDialog.getSaveFileName(self, "Save as...", '.',
            "ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)")

    self.setCurrentFileName(fn)
    return self.fileSave()

Assuming you just want to save the text entries in your list, this should work. 假设您只想将文本条目保存在列表中,这应该可以工作。 Beware that it will try and write a file to your disk. 请注意,它将尝试将文件写入磁盘。

import sys
import os
from PyQt4 import QtGui


class AnExample(QtGui.QMainWindow):
    def __init__(self):
        super(AnExample, self).__init__()

        self.buildUi()

    def buildUi(self):

        self.listWidget = QtGui.QListWidget()
        self.listWidget.addItems(['one',
                                  'two',
                                  'three'])

        warning = QtGui.QLabel("Warning, this progam can write to disk!")
        saveButton = QtGui.QPushButton('Save to location...')
        justSaveButton = QtGui.QPushButton('Just save!')
        saveButton.clicked.connect(self.onSave)
        justSaveButton.clicked.connect(self.onJustSave)

        grid = QtGui.QGridLayout()
        grid.addWidget(warning, 0, 0)
        grid.addWidget(self.listWidget, 1, 0)
        grid.addWidget(saveButton, 2, 0)
        grid.addWidget(justSaveButton, 3, 0)

        central = QtGui.QWidget()
        central.setLayout(grid)

        self.setCentralWidget(central)

    def onSave(self):
        self.saveFile(True)

    def onJustSave(self):
        self.saveFile(False)

    def saveFile(self, showDialog):
        """
        Function that will save list items to file.
        """
        # save to TESTING.txt in current working directory
        savePath = os.path.join(os.getcwd(),
                                'TESTING.txt')

        # allow user to override location if requested
        if showDialog:
            savePath = QtGui.QFileDialog.getSaveFileName(self,
                                                         'Save text file',
                                                         savePath,
                                                         'TESTING.txt')

        # if just saving, or user didn't cancel, make and save file
        if len(savePath) > 0:
            with open(savePath, 'w') as theFile:
                for i in xrange(self.listWidget.count()):
                    theFile.write(''.join([str(self.listWidget.item(i).text()),
                                           '\n']))


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = AnExample()
    ex.show()
    sys.exit(app.exec_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM