2

A common question on the net is how to display html using qstyleditemdelegate in a qlistview. The usual answer is a variant of the following code https://stackoverflow.com/a/5443112/2033030

class HTMLDelegate(QtGui.QStyledItemDelegate):
    def paint(self, painter, option, index):
        options = QtGui.QStyleOptionViewItemV4(option)
        self.initStyleOption(options,index)

        style = QtGui.QApplication.style() if options.widget is None else options.widget.style()

        doc = QtGui.QTextDocument()
        doc.setHtml(options.text)

        options.text = ""
        style.drawControl(QtGui.QStyle.CE_ItemViewItem, options, painter);

        ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
        if option.state & QStyle.State_Selected:
            ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText))
        else:
            ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText))


        textRect = style.subElementRect(QtGui.QStyle.SE_ItemViewItemText, options)
        painter.save()
        painter.translate(textRect.topLeft())
        painter.setClipRect(textRect.translated(-textRect.topLeft()))
        doc.documentLayout().draw(painter, ctx)

        painter.restore()

    def sizeHint(self, option, index):
        options = QtGui.QStyleOptionViewItemV4(option)
        self.initStyleOption(options,index)

        doc = QtGui.QTextDocument()
        doc.setHtml(options.text)
        doc.setTextWidth(options.rect.width())
        return QtCore.QSize(doc.idealWidth(), doc.size().height())

This is also what I used without really understanding it. So my main question is how to enable word wrap?I tried many things but never made it.

The second side question is, can someone explain me what that code does, it is a bit suspect in my eyes. First it create an optionS var from the original option parameter, but the code under seems to use one and the other ramdomly, so I suspect we could just use the option parameter without changes. then it requires to create two times the QTextDocument, both in paint and sizeHint. Then the style is used in DrawControl but not while drawing the QTextDocument....

I did keep both questions in one post so we hopefully together can come up to one example code that make sense and can be used by many as a start point.

Community
  • 1
  • 1
Olivier RD
  • 679
  • 1
  • 5
  • 11

1 Answers1

0

The solutio was to set text length for TextDocument

doc.setTextWidth(options.rect.width())

But this is very complicated so we reverted to using QListWidgets and now use QML

Olivier RD
  • 679
  • 1
  • 5
  • 11