4

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, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
        "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
        "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
        "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    ]

def get_html_box(text):
    return '''<table border="0" width="100%"><tr width="100%" valign="top">
        <td width="1%"><img src="softwarecenter.png"/></td>
        <td><table border="0" width="100%" height="100%">
        <tr><td><b><a href="http://www.google.com">titolo</a></b></td></tr>
        <tr><td>{0}</td></tr><tr><td align="right">88/88/8888, 88:88</td></tr>
        </table></td></tr></table>'''.format(text)

class HTMLDelegate(QStyledItemDelegate):

    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())
        painter.save()
        ctx = QAbstractTextDocumentLayout.PaintContext()
        ctx.clip = QRectF(0, option.rect.top(), option.rect.width(), option.rect.height())
        dl = doc.documentLayout()
        dl.draw(painter, ctx)
        painter.restore()

    def sizeHint(self, option, index):
        model = index.model()
        record = model.listdata[index.row()]
        doc = QTextDocument(self)
        doc.setHtml(get_html_box(record))
        doc.setTextWidth(option.rect.width())
        return QSize(doc.idealWidth(), doc.size().height())

class MyListModel(QAbstractListModel):

    def __init__(self, parent=None, *args):
        super(MyListModel, self).__init__(parent, *args)
        self.listdata = __data__

    def rowCount(self, parent=QModelIndex()):
        return len(self.listdata)

    def data(self, index, role=Qt.DisplayRole):
        return index.isValid() and QVariant(self.listdata[index.row()]) or QVariant()

class MyWindow(QWidget):

    def __init__(self, *args):
        super(MyWindow, self).__init__(*args)
        # listview
        self.lv = QListView()
        self.lv.setModel(MyListModel(self))
        self.lv.setItemDelegate(HTMLDelegate(self))
        self.lv.setResizeMode(QListView.Adjust)
        # layout
        layout = QVBoxLayout()
        layout.addWidget(self.lv)
        self.setLayout(layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

Element's size and position are not calculated correctly I guess, perhaps because I haven't understand at all the style related parts from original code. Can someone help me?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Giorgio Gelardi
  • 993
  • 4
  • 13
  • 29
  • Which element's size and position isn't being calculated correctly? Can you explain what you were expecting? – Kaleb Pederson Jun 02 '10 at 17:30
  • for me, each element's calculated height is wrong: when I run that code the list shows only the top element, higher than it should be (there's a lot of white space below), and I can't see other elements. – Giorgio Gelardi Jun 02 '10 at 17:59

1 Answers1

6

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()
Kaleb Pederson
  • 45,767
  • 19
  • 102
  • 147
  • 1
    I see. I really need to study a lot to understand why a common task like this require so much code. Perhaps I choose the worst way to do it. btw thank you very much for the correction. – Giorgio Gelardi Jun 02 '10 at 21:36
  • @GiorgioGelardi I actually think it's thing like these that make QT somewhat immature. Rich-text in ListViews would be really easy to include in QT by default (hell, they'd just have to copy this code over), and be invaluable! – WhyNotHugo Apr 07 '12 at 00:08
  • This code still causes a large empty space to be seen below every item (height miscalculation)? – WhyNotHugo Apr 07 '12 at 00:23