pythonpyqtpyqt4qfilesystemmodel

QFileSystemModel retrieve filepath of clicked file


I am trying to create a file explorer where you can look up a file. When found, the user should be able to select the file he want to upload. Therefore I need the path of the selected file.

Here is my current code:

import sys
from PyQt4.QtGui import *

class Explorer(QWidget):
    def __init__(self):
        super(Explorer, self).__init__()

        self.resize(700, 600)
        self.setWindowTitle("File Explorer")
        self.treeView = QTreeView()
        self.fileSystemModel = QFileSystemModel(self.treeView)
        self.fileSystemModel.setReadOnly(True)

        root = self.fileSystemModel.setRootPath("C:")
        self.treeView.setModel(self.fileSystemModel)

        Layout = QVBoxLayout(self)
        Layout.addWidget(self.treeView) 
        self.setLayout(Layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    fileExplorer = Explorer()
    fileExplorer .show()
    sys.exit(app.exec_())

How can I get the path of the file the user clicked on? Thanks for the help


Solution

  • In order to obtain the path we must use the QFileSystemModel::filePath() method:

    QString QFileSystemModel::filePath(const QModelIndex &index) const

    Returns the path of the item stored in the model under the index given.

    This requires a QModelIndex, this can be obtained through the clicked signal of QTreeView. For this we must connect it to some slot, in this case:

        self.treeView.clicked.connect(self.onClicked)
    
    def onClicked(self, index):
        # self.sender() == self.treeView
        # self.sender().model() == self.fileSystemModel
        path = self.sender().model().filePath(index)
        print(path)
    

    Complete code:

    import sys
    from PyQt4.QtGui import *
    
    class Explorer(QWidget):
        def __init__(self):
            super(Explorer, self).__init__()
    
            self.resize(700, 600)
            self.setWindowTitle("File Explorer")
            self.treeView = QTreeView()
            self.treeView.clicked.connect(self.onClicked)
            self.fileSystemModel = QFileSystemModel(self.treeView)
            self.fileSystemModel.setReadOnly(True)
    
            self.fileSystemModel.setRootPath("C:")
            self.treeView.setModel(self.fileSystemModel)
    
            Layout = QVBoxLayout(self)
            Layout.addWidget(self.treeView)
            self.setLayout(Layout)
    
        def onClicked(self, index):
            path = self.sender().model().filePath(index)
            print(path)
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        fileExplorer = Explorer()
        fileExplorer .show()
        sys.exit(app.exec_())