'Overloaded Qt method for custom painting of a model index'

def paint(self, painter, option, index):

    if (not self.highlight_text):
        return QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)
    text = index.data()
    if self.case_sensitive:
        html = text.replace(self.highlight_text, (u'<strong>%s</strong>' % self.highlight_text))
    else:
        match = re.match((u'(.*)(%s)(.*)' % re.escape(self.highlight_text)), text, re.IGNORECASE)
        if match:
            start = (match.group(1) or u'')
            middle = (match.group(2) or u'')
            end = (match.group(3) or u'')
            html = ((start + (u'<strong>%s</strong>' % middle)) + end)
        else:
            html = text
    self.doc.setHtml(html)
    params = QtWidgets.QStyleOptionViewItem(option)
    self.initStyleOption(params, index)
    params.text = u''
    style = QtWidgets.QApplication.style()
    style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, params, painter)
    ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
    if (params.state & QtWidgets.QStyle.State_Selected):
        color = params.palette.color(QtGui.QPalette.Active, QtGui.QPalette.HighlightedText)
        ctx.palette.setColor(QtGui.QPalette.Text, color)
    item_text = QtWidgets.QStyle.SE_ItemViewItemText
    rect = style.subElementRect(item_text, params, self.widget)
    painter.save()
    start = (rect.topLeft() + QtCore.QPoint(defs.margin, 0))
    painter.translate(start)
    self.doc.documentLayout().draw(painter, ctx)
    painter.restore()
