Skip to content Skip to sidebar Skip to footer

How To Make Item View Render Rich (html) Text In Pyqt?

I'm trying to translate code from this thread in python: import sys from PyQt4.QtCore import * from PyQt4.QtGui import * __data__ = [ 'Lorem ipsum dolor sit amet, consecte

Solution 1:

The code doesn't respect the desired target drawing area (option.rect):

ctx.clip = QRectF(0, option.rect.top(), option.rect.width(), option.rect.height())

The above clips the portion of the QTextDocument drawn to the specified region. You really want to translate the painter so that the it starts painting at the topLeft() of the rectangle and then extends for the specified width and height. Since documentLayout() assumes the painter is at the origin (i.e. in the position where it should draw), this is the fix:

def paint(self, painter, option, index):
    model = index.model()
    record = model.listdata[index.row()]
    doc = QTextDocument(self)
    doc.setHtml(get_html_box(record))
    doc.setTextWidth(option.rect.width())
    ctx = QAbstractTextDocumentLayout.PaintContext()

    painter.save()
    painter.translate(option.rect.topLeft());
    painter.setClipRect(option.rect.translated(-option.rect.topLeft()))
    dl = doc.documentLayout()
    dl.draw(painter, ctx)
    painter.restore()

Post a Comment for "How To Make Item View Render Rich (html) Text In Pyqt?"