-
-
Save z4none/a48ae901590429fbf758e021119c4602 to your computer and use it in GitHub Desktop.
QFileSystemModel and QSortFilterProxyModel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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