[英]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谢谢您的帮助
In order to obtain the path we must use the QFileSystemModel::filePath()
method:为了获得路径,我们必须使用QFileSystemModel::filePath()
方法:
QString QFileSystemModel::filePath(const QModelIndex &index) const 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.这需要一个QModelIndex,这个可以通过QTreeView的clicked信号获得。 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_())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.