[PyQt] vertical alignment of richtext in a table view

Mark Summerfield list at qtrac.plus.com
Tue Sep 7 07:56:49 BST 2010


On Tue, 7 Sep 2010 01:37:45 +0200
Wolfgang Rohdewald <wolfgang at rohdewald.de> wrote:
> On Montag 06 September 2010, Mark Summerfield wrote:
> > I'm tending to use a differnt approach for rich text delegates
> > nowadays. Instead of using a QTextDocument, I store a
> > class-level QLabel, something like this:
> 
> your solution certainly looks cleaner than my temporary fix
> (document.setDocumentMargin(7.0)), and it solves
> the problem of painting outside of the field.
> 
> but it does not quite work for me. Your untested example
> leaves the fields blank, it seems I have to give the
> renderer a position. Using view.pos() + option.rect.topLeft(), 
> labels are still too far up and left.
> The magical offset (3,25) puts them all in the right place.
> How can I compute the correct place instead?

I should have mentioned before that it is better to inherit from
QStyledItemDelegate rather than QItemDelegate. I'd try that first & see
if that improves things at all.

The offset you need _might_ be made up of the option.decorationSize's
width; not sure about the height offset.

Using QTextDocument is fine for computing the size hint, although for
efficiency you might create a class-level QTextDocument and reuse it.
(There are other possibilities too, that I cover in Advanced Qt
Programming, but can't recall off hand.)

> 
> class RichTextColumnDelegate(QtGui.QItemDelegate):
> 
>     label = QtGui.QLabel()
> 
>     def __init__(self, parent=None):
>         super(RichTextColumnDelegate, self).__init__(parent)
> 
>     def paint(self, painter, option, index):
>         text = index.model().data(index, 
> QtCore.Qt.DisplayRole).toString()
>         self.label.setText(text)
>         self.label.setFixedSize(option.rect.size())
>         view = self.parent().parent().view
>         topLeft = view.pos() + option.rect.topLeft() + 
> QtCore.QPoint(3, 25)
>         self.label.render(painter, topLeft)
> 
> 	def sizeHint(self,option,index):
> 		# still uses QTextDocument as in your book
> 
> 



-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "Rapid GUI Programming with Python and Qt" - ISBN 0132354187
            http://www.qtrac.eu/pyqtbook.html


More information about the PyQt mailing list