Skip to content

Instantly share code, notes, and snippets.

@z4none
Created July 22, 2020 09:08
Show Gist options
  • Save z4none/a48ae901590429fbf758e021119c4602 to your computer and use it in GitHub Desktop.
Save z4none/a48ae901590429fbf758e021119c4602 to your computer and use it in GitHub Desktop.
QFileSystemModel and QSortFilterProxyModel
class MyFileSystemModel(QFileSystemModel):
changed = pyqtSignal(str, int, int)
def __init__(self, parent=None):
self.checks = {}
super(MyFileSystemModel, self).__init__()
def flags(self, index):
return super(MyFileSystemModel, self).flags(index) | Qt.ItemIsUserCheckable
def checkState(self, index):
if index in self.checks:
return self.checks[index]
else:
return Qt.Unchecked
def data(self, index, role=Qt.DisplayRole):
if role != Qt.CheckStateRole:
return super(MyFileSystemModel, self).data(index, role)
if index.column() == 0:
path = super(MyFileSystemModel, self).filePath(index)
if os.path.isdir(path):
return super(MyFileSystemModel, self).data(index, role)
return self.checkState(index)
def setData(self, index, value, role=None):
if role == Qt.CheckStateRole and index.column() == 0:
self.checks[index] = value
self.changed.emit("dataChanged(QModelIndex,QModelIndex)", index, index)
return True
return super(MyFileSystemModel, self).setData(index, value, role)
class MySortFilter(QSortFilterProxyModel):
def lessThan(self, a, b):
model = self.sourceModel()
apath = model.filePath(a)
bpath = model.filePath(b)
return (not os.path.isdir(apath), apath) > (not os.path.isdir(bpath), bpath)
self.model = MyFileSystemModel()
self.model.setRootPath(QDir.currentPath())
self.proxy = MySortFilter()
self.proxy.setSourceModel(self.model)
tree = self.ui.treeView
tree.setModel(self.proxy)
idx = self.proxy.mapFromSource(self.model.index(root_dir))
tree.setRootIndex(idx)
tree.setSortingEnabled(True)
tree.setColumnWidth(0, 250)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment