summaryrefslogtreecommitdiff
path: root/tortoisehg/hgqt/htmldelegate.py
blob: 95b75077603cbf050bbdd45200b28d9b18c70614 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# htmldelegate.py - HTML QStyledItemDelegate
#
# Copyright 2010 Steve Borho <steve@borho.org>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2, incorporated herein by reference.

from __future__ import absolute_import

from .qtcore import (
    QPointF,
    QSize,
)
from .qtgui import (
    QAbstractTextDocumentLayout,
    QPalette,
    QStyle,
    QStyleOptionViewItemV4,
    QStyledItemDelegate,
    QTextDocument,
)

class HTMLDelegate(QStyledItemDelegate):

    def paint(self, painter, option, index):
        # draw selection
        option = QStyleOptionViewItemV4(option)
        self.parent().style().drawControl(QStyle.CE_ItemViewItem, option, painter)

        # draw text
        doc = self._builddoc(option, index)
        painter.save()
        painter.setClipRect(option.rect)
        painter.translate(QPointF(
            option.rect.left(),
            option.rect.top() + (option.rect.height() - doc.size().height()) / 2))
        ctx = QAbstractTextDocumentLayout.PaintContext()
        ctx.palette = option.palette
        if option.state & QStyle.State_Selected:
            if option.state & QStyle.State_Active:
                ctx.palette.setCurrentColorGroup(QPalette.Active)
            else:
                ctx.palette.setCurrentColorGroup(QPalette.Inactive)
            ctx.palette.setBrush(QPalette.Text, ctx.palette.highlightedText())
        elif not option.state & QStyle.State_Enabled:
            ctx.palette.setCurrentColorGroup(QPalette.Disabled)

        doc.documentLayout().draw(painter, ctx)
        painter.restore()

    def sizeHint(self, option, index):
        doc = self._builddoc(option, index)
        return QSize(doc.idealWidth() + 5, doc.size().height())

    def _builddoc(self, option, index):
        doc = QTextDocument(defaultFont=option.font)
        doc.setHtml(index.data())
        return doc