我正在尝试创建一个文件资源管理器,您可以在其中查找文件。找到后,用户应该能够选择要上传的文件。因此,我需要所选文件的路径。
这是我目前的代码:
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_())
如何获取用户点击的文件的路径? 谢谢你的帮助
答案 0 :(得分:1)
为了获得路径,我们必须使用function:
QString QFileSystemModel :: filePath(const QModelIndex& index)const
返回索引下模型中存储的项的路径 给出。
这需要一个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)
完整代码:
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_())