class MyStyledItemDelegate(QtWidgets.QStyledItemDelegate):
'''
For overriding behavior of selection and hovering in QTreeView and QTreeWidget
When you set background color (QtGui.QColor()) to QTreeWidgetItem you also must set this color like:
item.setData(0, QtCore.Qt.BackgroundRole, QtGui.QColor())
'''
def paint(self, painter, option, index):
def draw_my(option, painter, brush, text, icon):
if brush is None:
brush = QtGui.QColor(255, 255, 255, 0) # This is original background color. I just set alpha to 0 which means it is transparent
x, y = (option.rect.x(), option.rect.y())
h = option.rect.height()
painter.save()
painter.setFont(option.font)
if icon:
icon = icon.pixmap(h, h)
painter.drawPixmap(QtCore.QRect(x, y, h, h), icon)
painter.drawText(option.rect.adjusted(h, 0, 0, 0), QtCore.Qt.AlignLeft, text)
else:
painter.drawText(option.rect, QtCore.Qt.AlignLeft, text)
painter.setCompositionMode(QtGui.QPainter.CompositionMode_SourceAtop)
painter.setPen(QtGui.QPen(QtCore.Qt.NoPen))
painter.fillRect(option.rect, brush)
painter.setBackgroundMode(QtCore.Qt.OpaqueMode)
painter.setBackground(brush)
painter.drawRect(option.rect)
painter.restore()
# Also should be activated in StyleSheet
# Selected Hovered
if (option.state & QtWidgets.QStyle.State_Selected) or (option.state & QtWidgets.QStyle.State_MouseOver):
option.font.setWeight(QtGui.QFont.Bold)
brush = index.data(QtCore.Qt.BackgroundRole)
text = index.data(QtCore.Qt.DisplayRole)
icon = index.data(QtCore.Qt.DecorationRole)
draw_my(option=option, painter=painter, brush=brush, text=text, icon=icon)
else:
QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)
item.setBackground(0, QtGui.QBrush(QtGui.QColor(0, 255, 150, 100)))
item.setData(0, QtCore.Qt.BackgroundRole, QtGui.QColor(0, 255, 150,
100)) # 需要在 MyStyledItemDelegate 中绘制选定和悬停的数据