Reputation: 167
I would like to select files in a QTreeView and in the end I would like to get the path of the selected files, what should I do?
Here is a small example that I partly found on stackoverflow that I transformed a bit:
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_()
Help me please.
Upvotes: 0
Views: 338
Reputation: 6112
Use QFileSystemModel.filePath
to get the path of an item at a given QModelIndex.
class ArbreArborescence(QTreeView):
...
def currentChanged(self, current, previous):
print(self.model().filePath(current))
super().currentChanged(current, previous)
Upvotes: 1