class ButtonDelegate(widgets.StyledItemDelegate):
"""Delegate to show a button inside a table cell."""
ID = "button"
def __init__(
self,
parent: widgets.QAbstractItemView,
role: constants.ItemDataRole = constants.USER_ROLE,
):
super().__init__(parent)
parent.setMouseTracking(True)
self.btn = widgets.PushButton(parent=parent)
self.method_role = role
self.btn.hide()
self.current_edited_index = core.ModelIndex()
parent.entered.connect(self.cell_entered)
# parent.viewport().installEventFilter(self)
# def eventFilter(self, source, event) -> bool:
# if event.type() == event.Type.MouseMove:
# return True
# return super().eventFilter(source, event)
def updateEditorGeometry(
self,
editor: widgets.QWidget,
option: widgets.QStyleOptionViewItem,
index: core.ModelIndex,
):
editor.setGeometry(option.rect)
def createEditor(
self,
parent: widgets.QWidget,
option: widgets.QStyleOptionViewItem,
index: core.ModelIndex,
):
btn_callback = index.data(self.method_role)
if btn_callback is None:
return None
text = index.data()
return widgets.PushButton(
parent=parent,
text="" if text is None else str(text),
clicked=btn_callback,
)
def setEditorData(self, editor: widgets.QWidget, index: core.ModelIndex):
pass
# editor.setProperty("test", "aa")
# editor.setText(index.data())
def setModelData(
self,
editor: widgets.QWidget,
model: core.QAbstractItemModel,
index: core.ModelIndex,
):
pass
# model.setData(index, editor.property("test"))
def cell_entered(self, index: core.ModelIndex):
# index = self.parent().indexFromItem(item)
parent: widgets.QAbstractItemView = self.parent() # type: ignore
if self.current_edited_index.isValid() and parent.isPersistentEditorOpen(
self.current_edited_index
):
parent.closePersistentEditor(self.current_edited_index)
if parent.itemDelegateForIndex(index) is self:
# if index.data(self.method_role) is not None:
parent.openPersistentEditor(index)
parent.setCurrentIndex(index)
self.current_edited_index = index
def paint(
self,
painter: gui.QPainter,
option: widgets.QStyleOptionViewItem,
index: core.ModelIndex,
):
if index.data(self.method_role) is None:
super().paint(painter, option, index)
return
self.btn.setGeometry(option.rect)
text = index.data()
self.btn.setText("" if text is None else str(text))
if option.state & widgets.Style.StateFlag.State_MouseOver:
painter.fillRect(option.rect, option.palette.highlight())
if option.state & widgets.Style.StateFlag.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())
pixmap = self.btn.grab()
painter.drawPixmap(option.rect, pixmap)