neurocker
neurocker

Reputation: 174

PyQT - Displaying vertical text in QTableWidget cells

I found C++ code for my question, but I can't make it work using Python. I don't know C++, it's like recursion there...

class VerticalTextDelegate(QtGui.QStyledItemDelegate):
    def __init__(self, parent):
        super(VerticalTextDelegate, self).__init__()

    def paint(self, painter, option, index):
        optionCopy = QtGui.QStyleOptionViewItem(option)
        rectCenter = QtCore.QPointF(QtCore.QRectF(option.rect).center())
        painter.save()
        painter.translate(rectCenter.x(), rectCenter.y())
        painter.rotate(-90.0)
        painter.translate(-rectCenter.x(), -rectCenter.y())
        optionCopy.rect = painter.worldTransform().mapRect(option.rect)

        # recursion here, I don't understand how it works in C++
        # self.paint(painter, optionCopy, index)

        self.painter.restore()

    def sizeHint(self, option, index):
        val = QtGui.QSize(self.sizeHint(option, index))
        return QtGui.QSize(val.height(), val.width())

Running code:

    item = QtGui.QTableWidgetItem("test")
    self.table_widget.setItem(2, 0, item)

    self.table_widget.setItemDelegateForColumn(0,VerticalTextDelegate(self))

Upvotes: 0

Views: 456

Answers (1)

G.M.
G.M.

Reputation: 12879

If you look at the C++ example you refer to you'll see that the VerticalTextDelegate::paint implementation is basically fixing up the QPainter transform and then calling the base class implementation QStyledItemDelegate::paint. You need to do likewise (untested)...

def paint(self, painter, option, index):
    optionCopy = QtGui.QStyleOptionViewItem(option)
    rectCenter = QtCore.QPointF(QtCore.QRectF(option.rect).center())
    painter.save()
    painter.translate(rectCenter.x(), rectCenter.y())
    painter.rotate(-90.0)
    painter.translate(-rectCenter.x(), -rectCenter.y())
    optionCopy.rect = painter.worldTransform().mapRect(option.rect)

    # Call the base class implementation
    super(VerticalTextDelegate, self).paint(painter, optionCopy, index)

    painter.restore()

Upvotes: 1

Related Questions