PageRenderTime 34ms CodeModel.GetById 27ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/tortoisehg/hgqt/htmldelegate.py

https://bitbucket.org/tortoisehg/hgtk/
Python | 64 lines | 47 code | 8 blank | 9 comment | 7 complexity | 5bc09b7b058b9d17f6b913763f183149 MD5 | raw file
 1# htmldelegate.py - HTML QStyledItemDelegate
 2#
 3# Copyright 2010 Steve Borho <steve@borho.org>
 4#
 5# This software may be used and distributed according to the terms of the
 6# GNU General Public License version 2, incorporated herein by reference.
 7
 8from PyQt4.QtCore import *
 9from PyQt4.QtGui import *
10
11from mercurial import error
12from tortoisehg.hgqt import qtlib
13
14class HTMLDelegate(QStyledItemDelegate):
15    def __init__(self, parent=0, cols=None):
16        QStyledItemDelegate.__init__(self, parent)
17        self.cols = cols
18
19    def paint(self, painter, option, index):
20        if self.cols and index.column() not in self.cols:
21            return QStyledItemDelegate.paint(self, painter, option, index)
22        try:
23            text = index.model().data(index, Qt.DisplayRole).toString()
24        except error.RevlogError, e:
25            # this can happen if revlog is being truncated while we read it
26            text = _('?? Error: %s ??') % hglib.tounicode(str(e))
27
28        # draw selection
29        option = QStyleOptionViewItemV4(option)
30        self.parent().style().drawControl(QStyle.CE_ItemViewItem, option, painter)
31
32        # draw text
33        doc = QTextDocument(defaultFont=option.font)
34        painter.save()
35        doc.setHtml(text)
36        painter.setClipRect(option.rect)
37        painter.translate(QPointF(
38            option.rect.left(),
39            option.rect.top() + (option.rect.height() - doc.size().height()) / 2))
40        ctx = QAbstractTextDocumentLayout.PaintContext()
41        ctx.palette = option.palette
42        if option.state & QStyle.State_Selected:
43            if option.state & QStyle.State_Active:
44                ctx.palette.setCurrentColorGroup(QPalette.Active)
45            else:
46                ctx.palette.setCurrentColorGroup(QPalette.Inactive)
47            ctx.palette.setBrush(QPalette.Text, ctx.palette.highlightedText())
48        elif not option.state & QStyle.State_Enabled:
49            ctx.palette.setCurrentColorGroup(QPalette.Disabled)
50
51        doc.documentLayout().draw(painter, ctx)
52        painter.restore()
53
54    def sizeHint(self, option, index):
55        try:
56            text = index.model().data(index, Qt.DisplayRole).toString()
57        except error.RevlogError, e:
58            text = _('?? Error: %s ??') % hglib.tounicode(str(e))
59        doc = QTextDocument()
60        doc.setDefaultStyleSheet(qtlib.thgstylesheet)
61        doc.setDefaultFont(option.font)
62        doc.setHtml(text)
63        doc.setTextWidth(option.rect.width())
64        return QSize(doc.idealWidth() + 5, doc.size().height())