可以使用QStyledItemDelegate来实现在QStandardItem中添加背景颜色。具体实现步骤如下:
- 继承QStyledItemDelegate,重写paint方法。
- 在paint方法中获取文本内容,并查找关键字的位置。
- 使用QStylePainter绘制item背景和文本,如果匹配到关键字则设置对应区域的背景颜色。
示例代码如下:
class CustomDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super().__init__(parent)
def paint(self, painter, option, index):
# 获取文本内容
text = index.data(Qt.DisplayRole)
# 设置选中状态
if option.state & QStyle.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())
# 设置关键字的背景颜色
keyword = "test"
start_pos = 0
while True:
pos = text.find(keyword, start_pos)
if pos == -1:
break
# 计算关键字所在矩形区域
font_metrics = QFontMetrics(option.font)
rect = font_metrics.boundingRect(text[pos:pos + len(keyword)])
rect.moveLeft(option.rect.x() + font_metrics.width(text[:pos]))
# 绘制矩形区域并填充颜色
painter.save()
painter.setBrush(Qt.yellow)
painter.drawRect(rect.adjusted(-1, -1, 0, 0))
painter.restore()
start_pos = pos + len(keyword)
# 绘制文本内容
self.drawDisplay(painter, option, option.rect, text)
def sizeHint(self, option, index):
return QSize(0, 20)
使用以上代码创建delegate,然后在QStandardItemModel中设置该delegate即可实现在QStandardItem中添加背景颜色。
内容由零声教学AI助手提供,问题来源于学员提问




