PYQT files paths to tree
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开发者_StackOverflow 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.
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
精彩评论