QFileSystemModel 检索点击文件的文件路径

QFileSystemModel retrieve filepath of clicked file

我正在尝试创建一个文件资源管理器,您可以在其中查找文件。找到后,用户应该可以 select 他要上传的文件。因此我需要 selected 文件的路径。

这是我当前的代码:

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

如何获取用户点击文件的路径? 感谢帮助

为了获取路径我们必须使用QFileSystemModel::filePath()方法:

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

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

这需要一个QModelIndex,这个可以通过QTreeView的clicked信号得到。为此,我们必须将它连接到某个插槽,在这种情况下:

    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)

完整代码:

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