Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PYQT files paths to tree

Tags:

python

pyqt

I'm working on a project in which I need to display some folders in a Tree view. I have a list of full file paths like:

  • C:\folder1\file1
  • C:\folder1\folder11\file2
  • C:\folder2\file3

etc

Well the file paths are actually stored in a sql server which I aquire by running a query.

I'm looking for a way to put this into a QTreeView.

I have tried using the QFileSystemModel and using setNameFilters but this does not work as you can not enter paths into the filter.

Somebody suggest using a QSortFilterProxyModel but I have no idea how to do this.

Thanks.

Tom.

like image 410
supertom44 Avatar asked May 29 '26 15:05

supertom44


1 Answers

Pls, see if an example below would work for you:

import sys
from PyQt4 import QtGui, QtCore

class TestSortFilterProxyModel(QtGui.QSortFilterProxyModel):
    def __init__(self, parent=None):
        super(TestSortFilterProxyModel, self).__init__(parent)
        self.filter = ['folder0/file0', 'folder1/file1'];

    def filterAcceptsRow(self, source_row, source_parent):
        index0 = self.sourceModel().index(source_row, 0, source_parent)
        filePath = self.sourceModel().filePath(index0) 

        for folder in self.filter:
            if filePath.startsWith(folder) or QtCore.QString(folder).startsWith(filePath):
                return True;        
        return False    

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        model = QtGui.QFileSystemModel(self)
        model.setRootPath(QtCore.QDir.currentPath())

        proxy = TestSortFilterProxyModel(self)
        proxy.setSourceModel(model)     

        self.view = QtGui.QTreeView()
        self.view.setModel(proxy)

        self.setCentralWidget(self.view)

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

hope this helps, regards

like image 62
serge_gubenko Avatar answered Jun 01 '26 05:06

serge_gubenko