You can subclass QDirModel and override the data(index,role) method, where you should check if role is QtCore.Qt.CheckStateRole . If so, you should return either QtCore.Qt.Checked or QtCore.Qt.Unchecked . In addition, you need to override the setData method to handle user checks / undo and flags to return the QtCore.Qt.ItemIsUserCheckable flag, which allows the user to check / uncheck. I.e:.
class CheckableDirModel(QtGui.QDirModel): def __init__(self, parent=None): QtGui.QDirModel.__init__(self, None) self.checks = {} def data(self, index, role=QtCore.Qt.DisplayRole): if role != QtCore.Qt.CheckStateRole: return QtGui.QDirModel.data(self, index, role) else: if index.column() == 0: return self.checkState(index) def flags(self, index): return QtGui.QDirModel.flags(self, index) | QtCore.Qt.ItemIsUserCheckable def checkState(self, index): if index in self.checks: return self.checks[index] else: return QtCore.Qt.Unchecked def setData(self, index, value, role): if (role == QtCore.Qt.CheckStateRole and index.column() == 0): self.checks[index] = value self.emit(QtCore.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) return True return QtGui.QDirModel.setData(self, index, value, role)
Then you use this class instead of QDirModel :
model = CheckableDirModel() tree = QtGui.QTreeView() tree.setModel(model)
source share