3

我有许多带有很长标签的窄列。我想将标签旋转 90 度。可能吗?

4

3 回答 3

3

您可能必须继承 QTableWidgetItem并实现您自己的垂直文本绘制。然后setHorizontalHeaderItem()在您的表上使用以指向您的新小部件的一个实例。

于 2010-09-06T18:16:56.107 回答
2

在寻找这个问题的答案时,我发现了很多提示,但没有真正的答案。提示告诉人们继承 QHeaderView 并重新实现paintSection。当我尝试在 PyQt4 中这样做并尝试按照 QHeaderView 的源代码从头开始实现paintSection 时,我没有成功。然而,简单地旋转画家实例并调整所有尺寸提示是成功的。该代码仅适用于水平标题,并且非常紧凑:

from PyQt4 import QtGui, QtCore

class RotatedHeaderView( QtGui.QHeaderView ):
    def __init__(self, orientation, parent=None ):
        super(RotatedHeaderView, self).__init__(orientation, parent)
        self.setMinimumSectionSize(20)

    def paintSection(self, painter, rect, logicalIndex ):
        painter.save()
        # translate the painter such that rotate will rotate around the correct point
        painter.translate(rect.x()+rect.width(), rect.y())
        painter.rotate(90)
        # and have parent code paint at this location
        newrect = QtCore.QRect(0,0,rect.height(),rect.width())
        super(RotatedHeaderView, self).paintSection(painter, newrect, logicalIndex)
        painter.restore()

    def minimumSizeHint(self):
        size = super(RotatedHeaderView, self).minimumSizeHint()
        size.transpose()
        return size

    def sectionSizeFromContents(self, logicalIndex):
        size = super(RotatedHeaderView, self).sectionSizeFromContents(logicalIndex)
        size.transpose()
        return size
于 2014-02-11T04:01:25.327 回答
2

我已经根据先前的答案制作了一个可以正常工作的自定义脚本..

将下一个代码复制并粘贴到 rotate.py 文件中

#!/usr/bin/env python

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class RotatedHeaderView(QHeaderView):
    def __init__(self, parent=None):
        super(RotatedHeaderView, self).__init__(Qt.Horizontal, parent)
        self.setMinimumSectionSize(20)

    def paintSection(self, painter, rect, logicalIndex ):
        painter.save()
        # translate the painter such that rotate will rotate around the correct point
        painter.translate(rect.x()+rect.width(), rect.y())
        painter.rotate(90)
        # and have parent code paint at this location
        newrect = QRect(0,0,rect.height(),rect.width())
        super(RotatedHeaderView, self).paintSection(painter, newrect, logicalIndex)
        painter.restore()

    def minimumSizeHint(self):
        size = super(RotatedHeaderView, self).minimumSizeHint()
        size.transpose()
        return size

    def sectionSizeFromContents(self, logicalIndex):
        size = super(RotatedHeaderView, self).sectionSizeFromContents(logicalIndex)
        size.transpose()
        return size

然后使用以下行从您的 main.py 文件中导入此类:

from rotated import RotatedHeaderView

并使用此行完成操作:

self.YourTableName.setHorizontalHeader(RotatedHeaderView(self.YourTableName))

希望值得!

于 2016-03-11T04:57:50.137 回答