Search code examples
pythonpyqtqlistwidgetqfiledialog

Fill a QListWidget using getOpenFileNames


In the example below, I would like to fill my QListWidget with files opening a Qdialog. I don't understand how I can add the files selected in the list. Should I do a new class? How can I connect the two methods setupList and addFiles?

import sys
from PyQt4 import QtCore, QtGui

from datapath import *

class MainWindow(QtGui.QMainWindow):

    def __init__(self):
        super(MainWindow,self).__init__()

        self.sources =[]

        self.setupActions()
        self.setupList()
        self.setupUi()
        self.setupStatusBars()

    def addFiles(self):
        files = QtGui.QFileDialog.getOpenFileNames(
            self,"Open File", dirpath, "txt Files (*.txt)")

        for string in files:
            self.sources.append(str(string))

        return self.sources

    def setupActions(self):
        self.exitAct = QtGui.QAction(
            QtGui.QIcon(':/images/exit.png'),
            "E&xit", self, shortcut="Ctrl+Q",
            statusTip="Exit the application", triggered=self.close
            )

        self.addFilesAct = QtGui.QAction(
            QtGui.QIcon(':/images/open.png'),
            "Add &Files", self, shortcut=QtGui.QKeySequence.Open,
            statusTip="Open an existing file", triggered=self.addFiles
            )

    def setupList(self):
        #FileList
        self.FileList = QtGui.QListWidget(self)
        self.FileList.addItems(self.sources)

    def setupUi(self):
        #Window size
        horiz = 300
        vert  = 300
        self.setGeometry(self.width()/2, self.height()/2,horiz,vert)
        self.setWindowTitle("test")

        #MenuBar
        self.FileMenu = self.menuBar().addMenu("&File")
        self.FileMenu.addAction(self.addFilesAct)
        self.FileMenu.addSeparator();
        self.FileMenu.addAction(self.exitAct)

        #ToolBar
        self.fileToolBar = self.addToolBar("Open")
        self.fileToolBar.addAction(self.addFilesAct)
        self.fileToolBar.setIconSize(QtCore.QSize(64,64))

        #Build Layout
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.FileList)

        widget = QtGui.QWidget()
        widget.setLayout(mainLayout)

        self.setCentralWidget(widget)

    def setupStatusBars(self):
        self.statusBar().showMessage("Ready")


def main():
    app = QtGui.QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())

if __name__ == '__main__':

    main()

Solution

  • When self.sources is changed, the elements of the QListWidget will not change. So self.FileList.addItems(self.sources) in setupList() should be removed and instead put in addFiles() so that every time the files are selected in the dialog, the QListWidget's addItems method is called. Then return self.sources in addFiles() would be unnecessary.