06 октября 2009

Отображение rich text в item view.

Понадобилось мне тут отображать rich text в QTableView. По умолчанию такого поведения нет и полез я в исходники. Оказывается всё необходимое для сего есть. Посмотрел я на QLabel и наваял следующее:

from PyQt4.QtCore import Qt
from PyQt4.QtGui import *

class RichTextItemDelegete(QAbstractItemDelegate):
def __init__(self, parent):
QAbstractItemDelegate.__init__(self, parent)

def paint(self, painter, option, index):
if option.state & QStyle.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())

painter.setBrush(QColor(Qt.black))
document = QTextDocument()
document.setHtml(index.data(Qt.DisplayRole).toString())
context = QAbstractTextDocumentLayout.PaintContext()
context.palette = option.palette

if option.state & QStyle.State_Selected:
context.palette.setColor(QPalette.Text, Qt.white)
else:
context.palette.setColor(QPalette.Text, Qt.black);

painter.save()
layout = document.documentLayout()
painter.translate(0, option.rect.y())
layout.draw(painter, context)
painter.restore()

def sizeHint(self, option, index):
document = QTextDocument()
document.setHtml(index.data(Qt.DisplayRole).toString())
layout = document.documentLayout()
return layout.documentSize().toSize()


Код как видите на питоне, но на С++ переносится чуть-ли не копипастой.