Python 3.x 在QTreeView中检索选定文件的路径

Python 3.x 在QTreeView中检索选定文件的路径,python-3.x,pyqt5,Python 3.x,Pyqt5,我想在QTreeView中选择文件,最后我想获得所选文件的路径,我该怎么做 下面是我在stackoverflow上发现的一个小例子,我对其进行了一些转换: from PyQt5.QtCore import QDir, Qt from PyQt5.QtWidgets import QFileSystemModel, QTreeView, QAbstractItemView, QApplication, QFileIconProvider from PyQt5.QtGui import QIcon

我想在QTreeView中选择文件,最后我想获得所选文件的路径,我该怎么做

下面是我在stackoverflow上发现的一个小例子,我对其进行了一些转换:

from PyQt5.QtCore import QDir, Qt
from PyQt5.QtWidgets import QFileSystemModel, QTreeView, QAbstractItemView, QApplication, QFileIconProvider
from PyQt5.QtGui import QIcon

import sys, os

from chemin_data_ressources import chemin_ressources

class ArbreArborescence(QTreeView):
    def __init__(self, parent=None):
        super(ArbreArborescence, self).__init__(parent)
    
        self.setDragEnabled(True)
        self.setDragDropMode(QAbstractItemView.DragOnly)
        self.setDefaultDropAction(Qt.CopyAction)
        self.setAlternatingRowColors(True)
        self.setSelectionMode(QAbstractItemView.SingleSelection)

        self.setStyleSheet("background-color: rgb(180, 180, 180);alternate-background-color: rgb(180, 180, 180);")


    def set_source(self, folder):
        """ """
        self.up_folder = os.path.dirname(folder)
        self.dirModel = QFileSystemModel()
        self.dirModel.setRootPath(QDir.homePath()) # Sous windows QDir.Drives() éventuellement
        self.setModel(self.dirModel)
        self.setRootIndex(self.dirModel.index(self.up_folder)) #
        self.setWordWrap(True)
        self.hideColumn(1)
        self.hideColumn(2)
        self.hideColumn(3)
        idx = self.dirModel.index(folder)
        self.expand(idx)
        self.scrollTo(idx, QAbstractItemView.EnsureVisible)
    
        self.dirModel.setNameFilters(["*.jpg", "*.jpeg", "*.png", "*.gif"])
        self.dirModel.setNameFilterDisables(False)
    
        self.dirModel.setIconProvider(IconProvider()) 
    
    
class IconProvider(QFileIconProvider):

    def icon(self, fileInfo):
        if fileInfo.isDir():
            return QIcon(chemin_ressources(os.path.join('ressources_murexpo', 'icone_png_dossier_apsc_256x256.png'))) 
        return QFileIconProvider.icon(self, fileInfo)


if __name__=='__main__':
    app = QApplication(sys.argv)
    w = ArbreArborescence()
    w.set_source(os.path.expanduser('~')) # Fonctionne ! (ou '/home')
    w.show()
    app.exec_()

请帮帮我。

使用
QFileSystemModel.filePath
获取给定QModelIndex处项目的路径

class ArbreArborescence(QTreeView):
    ...
    def currentChanged(self, current, previous):
        print(self.model().filePath(current))
        super().currentChanged(current, previous)

万分感谢亚历克,它工作得很好!,这正是我想要的。