QFileSystemModel检索单击fi的文件路径

2024-04-26 05:53:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个文件资源管理器,您可以在其中查找文件。当找到时,用户应该能够选择他想要上传的文件。因此,我需要所选文件的路径。在

以下是我当前的代码:

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

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


Tags: 文件代码用户importself路径appinit
1条回答
网友
1楼 · 发布于 2024-04-26 05:53:50

为了获得路径,我们必须使用function

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

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

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

    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)

完整代码:

^{pr2}$

相关问题 更多 >