简体   繁体   中英

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))

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM