Little warning: QItemDelegate / QStyledItemDelegate goes deep to rabbit hole of Qt’s view / model / delegate programming. Here is small working example (tested on Kubuntu Krita5)
from dataclasses import (
dataclass,)
from krita import (
Krita,)
from PyQt5.QtCore import (
Qt,
pyqtSlot as QSlot,
pyqtSignal as QSignal,
pyqtProperty as QProperty,
QEvent,
QSize,
QRect,
QModelIndex,
QAbstractListModel)
from PyQt5.QtGui import (
QPainter,
QKeySequence)
from PyQt5.QtWidgets import (
QApplication,
QStyle,
QWidget,
QHBoxLayout,
QListView,
QStyledItemDelegate,
QStyleOptionViewItem,
QStyleOptionButton,
QStyleOptionToolButton,
QCheckBox,
QLineEdit,
QToolButton)
@dataclass
class MyItem:
checked: bool = True
name: str = ''
option_a: bool = False
option_b: bool = False
class MyItemEditor(QWidget):
value_changed = QSignal(MyItem)
def __init__(self, **kwargs):
self._enabled_check = QCheckBox(text='enabled')
self._name_edit = QLineEdit(placeholderText='name...')
self._option_a_button = QToolButton(text='A', checkable=True)
self._option_b_button = QToolButton(text='B', checkable=True)
super().__init__(**kwargs)
layout = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setLayout(layout)
layout.addWidget(self._enabled_check)
layout.addWidget(self._name_edit, stretch=100)
layout.addWidget(self._option_a_button)
layout.addWidget(self._option_b_button)
self.setAutoFillBackground(True)
def value(self):
my_item = MyItem(
self._enabled_check.isChecked(),
self._name_edit.text(),
self._option_a_button.isChecked(),
self._option_b_button.isChecked())
return my_item
def set_value(self, new_value):
if not isinstance(new_value, MyItem):
raise TypeError('Value must be type of MyItem.')
if new_value == self.value():
return # nothing to do
self._enabled_check.setChecked(new_value.checked)
self._name_edit.setText(new_value.name)
self._option_a_button.setChecked(new_value.option_a)
self._option_b_button.setChecked(new_value.option_b)
self.value_changed.emit(self.value())
# note: property is set to be "user" property, so that editor works with default
# QStyledItemDelegate.setEditorData(...) and QStyledItemDelegate.setModelData(...)
value_prop = QProperty(
MyItem,
fget=value,
fset=set_value,
user=True,
notify=value_changed)
def sizeHint(self):
return QSize(200, 28)
class MyListModel(QAbstractListModel):
def __init__(self, **kwargs):
self._items = list()
super().__init__(**kwargs)
# populate model, with some test data
self._items.extend([
MyItem(name='my item 01'),
MyItem(name='my item 02'),
MyItem(name='my item 03'),
MyItem(name='my item 04')])
def rowCount(self, index=QModelIndex()):
if index.isValid():
# this model is strict list, tree indexing is NOT supported.
return 0
return len(self._items)
def flags(self, index):
return super().flags(index) | Qt.ItemIsEditable
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.EditRole:
return self._items[index.row()]
if role == Qt.DisplayRole:
# note: this is not used in MyItemDelegate(), but implemented for ease of use.
my_item = self._items[index.row()]
return f'{my_item.checked = } {my_item.name = } {my_item.option_a = } {my_item.option_b = }'
return None
def setData(self, index, new_value, role=Qt.EditRole):
if index.isValid():
if role == Qt.EditRole:
self._items[index.row()] = new_value
self.dataChanged.emit(index, index)
return True
return False
def headerData(self, section, orientation, role=Qt.DisplayRole):
if (section == 0) and (orientation == Qt.Hoorizontal) and (role == Qt.DisplayRole):
return 'name'
return None
class MyItemDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
my_item = index.data(role=Qt.EditRole)
if isinstance(my_item, MyItem):
self._draw_my_item(painter, option, index, my_item)
else:
super().paint(painter, option, index)
def _rects(self, option, index):
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
rect = opt.rect
height = rect.height()
check_rect = QRect(rect)
check_rect.setRight(rect.left() + 80)
option_b_rect = QRect(rect)
option_b_rect.setLeft(rect.right() - height)
option_a_rect = QRect(rect)
option_a_rect.setLeft(option_b_rect.left() - height)
option_a_rect.setRight(option_b_rect.left())
text_rect = QRect(rect)
text_rect.setLeft(check_rect.right())
text_rect.setRight(option_a_rect.left())
return check_rect, text_rect, option_a_rect, option_b_rect
def _draw_my_item(self, painter, option, index, my_item):
widget = option.widget
style = QApplication.style() if widget is None else widget.style()
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
check_rect, text_rect, option_a_rect, option_b_rect = self._rects(option, index)
opt.text = my_item.name
opt.rect = text_rect
check_opt = QStyleOptionButton()
check_opt.font = opt.font
check_opt.displayAlignment = opt.displayAlignment
check_opt.palette = opt.palette
check_opt.direction = opt.direction
check_opt.fontMetrics = opt.fontMetrics
check_opt.text = 'enabled'
check_opt.rect = check_rect
check_opt.state = opt.state
check_opt.state |= QStyle.State_On if my_item.checked else QStyle.State_Off
button_a_opt = QStyleOptionToolButton()
button_a_opt.font = opt.font
button_a_opt.displayAlignment = opt.displayAlignment
button_a_opt.palette = opt.palette
button_a_opt.direction = opt.direction
button_a_opt.fontMetrics = opt.fontMetrics
button_a_opt.subControls = QStyle.SC_ToolButton
button_a_opt.activeSubControls = QStyle.SC_None
button_a_opt.text = 'A'
button_a_opt.rect = option_a_rect
button_a_opt.state = opt.state & QStyle.State_Enabled
if my_item.option_a:
button_a_opt.state |= QStyle.State_On | QStyle.State_Sunken
else:
button_a_opt.state |= QStyle.State_Off | QStyle.State_Raised
button_b_opt = QStyleOptionToolButton()
button_b_opt.font = opt.font
button_b_opt.displayAlignment = opt.displayAlignment
button_b_opt.palette = opt.palette
button_b_opt.direction = opt.direction
button_b_opt.fontMetrics = opt.fontMetrics
button_b_opt.subControls = QStyle.SC_ToolButton
button_b_opt.activeSubControls = QStyle.SC_None
button_b_opt.text = 'B'
button_b_opt.rect = option_b_rect
button_b_opt.state = opt.state & QStyle.State_Enabled
if my_item.option_b:
button_b_opt.state |= QStyle.State_On | QStyle.State_Sunken
else:
button_b_opt.state |= QStyle.State_Off | QStyle.State_Raised
style.drawControl(QStyle.CE_CheckBox, check_opt, painter, widget)
style.drawItemText(painter, opt.rect, opt.displayAlignment, opt.palette, opt.state, opt.text)
style.drawComplexControl(QStyle.CC_ToolButton, button_a_opt, painter, widget)
style.drawComplexControl(QStyle.CC_ToolButton, button_b_opt, painter, widget)
def createEditor(self, parent, option, index):
my_item = index.data(role=Qt.EditRole)
if isinstance(my_item, MyItem):
return MyItemEditor(parent=parent)
return super().createEditor(parent, option, index)
def setModelData(self, editor, model, index):
if isinstance(editor, MyItemEditor):
# fix to bug in PyQt5, (failed to convert MyItem() -> PyQt_PyObject ???)
model.setData(index, editor.value(), role=Qt.EditRole)
else:
super().setModelData(editor, model, index)
def sizeHint(self, option, index):
return QSize(200, 28)
def editorEvent(self, event, model, option, index):
if event.type() in {QEvent.MouseMove, QEvent.MouseButtonPress, QEvent.MouseButtonRelease}:
my_item = index.data(role=Qt.EditRole)
if isinstance(my_item, MyItem):
pos = event.pos()
check_rect, text_rect, option_a_rect, option_b_rect = self._rects(option, index)
if check_rect.contains(pos):
print(f'Debug: editorEvent in check enabled rect {event = }, {my_item = }')
if event.type() == QEvent.MouseButtonRelease:
# toggle on release (should also check that press was done at same area.)
my_item.checked = not my_item.checked
model.setData(index, my_item, role=Qt.EditRole)
elif text_rect.contains(pos):
print(f'Debug: editorEvent in text rect {event = }, {my_item = }')
# maybe add SelectedClicked to QAbstractItemView.setEditTriggers(
# QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked | QAbstractItemView.EditKeyPressed)
elif option_a_rect.contains(pos):
print(f'Debug: editorEvent in option_a rect {event = }, {my_item = }')
if event.type() == QEvent.MouseButtonRelease:
# toggle on release (should also check that press was done at same area.)
my_item.option_a = not my_item.option_a
model.setData(index, my_item, role=Qt.EditRole)
elif option_b_rect.contains(pos):
print(f'Debug: editorEvent in option_b rect {event = }, {my_item = }')
if event.type() == QEvent.MouseButtonRelease:
# toggle on release (should also check that press was done at same area.)
my_item.option_b = not my_item.option_b
model.setData(index, my_item, role=Qt.EditRole)
return super().editorEvent(event, model, option, index)
# def updateEditorGeometry(self, editor, option, index):
# pass
#
# def setEditorData(self, editor, index):
# super().setEditorData(editor, index)
_keep_alive = None
def testing():
global _keep_alive
my_view = QListView()
my_view.setModel(MyListModel(parent=my_view))
my_view.setItemDelegate(MyItemDelegate(parent=my_view))
my_view.show()
_keep_alive = my_view
testing()
Have fun in this rabbit hole.
/AkiR