I am using QTableView\'s checkbox flag of Qt::ItemIsUserCheckable to display a checkbox in a table cell.
After reading some things on alignment in an attempt to
Solution for Python (PySide, PyQt) to center the checkbox and with editable allowed:
class BooleanDelegate(QItemDelegate):
def __init__(self, *args, **kwargs):
super(BooleanDelegate, self).__init__(*args, **kwargs)
def paint(self, painter, option, index):
# Depends on how the data function of your table model is implemented
# 'value' should recive a bool indicate if the checked value.
value = index.data(Qt.CheckStateRole)
self.drawCheck(painter, option, option.rect, value)
self.drawFocus(painter, option, option.rect)
def editorEvent(self, event, model, option, index):
if event.type() == QEvent.MouseButtonRelease:
value = bool(model.data(index, Qt.CheckStateRole))
model.setData(index, not value)
event.accept()
return super(BooleanDelegate, self).editorEvent(event, model, option, index)
In your table model, make sure that the flags allow the user to check/uncheck the cell.
class MyTableModel(QAbstractTableModel):
...
def flags(self, index):
if not index.isValid():
return Qt.ItemIsEnabled
if index.column() in self.columns_boolean:
return Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
return Qt.ItemFlags(QAbstractTableModel.flags(self, index) | Qt.ItemIsEditable)
Finally, set the BooleanDelagate
in your table
self.boolean_delegate = BooleanDelegate()
self.input_gui.setItemDelegateForColumn(5, self.boolean_delegate)