您可以继承 QDirModel,并重新实现data(index,role)
方法,您应该检查,如果role
是QtCore.Qt.CheckStateRole
。如果是,您应该返回QtCore.Qt.Checked
或QtCore.Qt.Unchecked
。此外,您还需要重新实现setData
方法,以处理用户检查/取消检查,并flags
返回 QtCore.Qt.ItemIsUserCheckable 标志,该标志启用用户检查/取消检查。IE:
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)
然后你使用这个类而不是QDirModel
:
model = CheckableDirModel()
tree = QtGui.QTreeView()
tree.setModel(model)