[PyQt] vertical alignment of richtext in a table view
Mark Summerfield
list at qtrac.plus.com
Mon Sep 6 17:41:22 BST 2010
Hi Wolfgang,
On Sun, 5 Sep 2010 10:55:04 +0200
Wolfgang Rohdewald <wolfgang at rohdewald.de> wrote:
> Hi,
>
> in Mark Summerfields book "Rapid GUI programming with Python
> and QT", there is an example on page 485 with a table column
> having a delegate that displays richtext. In the book,
> the text in this column has a vertical alignment in the middle
> of the cells, just like the other columns.
>
> but if I execute that example (from the downloadable source:
> chap16/carhirelog.pyw), the rich text is vertically not
> in the middle but above. How can I make it align vertically
> just like a normal column?
>
> His book has another such table chap14, page 436 /
> ships_delegate.pyw.
> Here, both the image in the book and the executable show
> the same wrong vertical alignment.
>
> BTW interesting things happen if the column with richtext
> is resized to a minimum: the delegate draws outside of its
> available horizontal space, showing text to the right of
> the rightmost column.
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:
# UNTESTED!
def paint(self, painter, option, index):
text = index.model().data(index, Qt.DisplayRole).toString()
self.label.setText(text) # self.label is a QLabel with alignment
# etc. set up as one likes in the
# delegate's constructor
# might want to change the label's palette here, depending on
# the selection state
self.label.setFixedSize(option.rect)
self.label.render(painter)
Hope this helps:-)
> (using pyqt 4.7.3 with qt4-4.7.0-rc1)
>
> this is the paint of the delegate:
>
> def paint(self, painter, option, index):
> text = index.model().data(index, Qt.DisplayRole).toString()
> palette = QApplication.palette()
> document = QTextDocument()
> document.setDefaultFont(option.font)
> if option.state & QStyle.State_Selected:
> document.setHtml(QString("<font color=%1>%2</font>") \
> .arg(palette.highlightedText().color().name()) \
> .arg(text))
> else:
> document.setHtml(text)
> painter.save()
> color = palette.highlight().color() \
> if option.state & QStyle.State_Selected \
> else QColor(index.model().data(index,
> Qt.BackgroundColorRole))
> painter.fillRect(option.rect, color)
> painter.translate(option.rect.x(), option.rect.y())
> document.drawContents(painter)
> painter.restore()
>
>
--
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