def paint(self, painter, option, index): """Overloaded Qt method for custom painting of a model index""" if not self.highlight_text: return QtGui.QStyledItemDelegate.paint(self, painter, option, index) text = ustr(index.data().toPyObject()) if self.case_sensitive: html = text.replace(self.highlight_text, '<strong>%s</strong>' % self.highlight_text) else: match = re.match(r'(.*)(%s)(.*)' % re.escape(self.highlight_text), text, re.IGNORECASE) if match: start = match.group(1) or '' middle = match.group(2) or '' end = match.group(3) or '' html = (start + ('<strong>%s</strong>' % middle) + end) else: html = text self.doc.setHtml(html) # Painting item without text, Text Document will paint the text optionV4 = QtGui.QStyleOptionViewItemV4(option) self.initStyleOption(optionV4, index) optionV4.text = QtCore.QString() style = QtGui.QApplication.style() style.drawControl(QtGui.QStyle.CE_ItemViewItem, optionV4, painter) ctx = QtGui.QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected if (optionV4.state & QtGui.QStyle.State_Selected): color = optionV4.palette.color(QtGui.QPalette.Active, QtGui.QPalette.HighlightedText) ctx.palette.setColor(QtGui.QPalette.Text, color) # translate the painter to where the text is drawn rect = style.subElementRect(QtGui.QStyle.SE_ItemViewItemText, optionV4) painter.save() start = rect.topLeft() + QtCore.QPoint(3, 0) painter.translate(start) # tell the text document to draw the html for us self.doc.documentLayout().draw(painter, ctx) painter.restore()