Qt - QTable可以将列标签旋转90度吗?

时间:2010-09-06 13:12:45

标签: qt qtablewidget

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

3 个答案:

答案 0 :(得分:3)

您可能需要继承QTableWidgetItem并实现自己的垂直文本绘画。然后使用表格上的setHorizontalHeaderItem()指向新小部件的实例。

答案 1 :(得分:2)

在寻找这些问题的答案时,我发现了许多提示,但没有真正的答案。提示告诉一个子类QHeaderView并重新实现paintSection。当我在PyQt4中尝试这样做并尝试从头开始实现paintSection时,遵循QHeaderView的源代码,我没有成功。但是,只需旋转画家实例并调整所有大小提示即可成功。 该代码仅适用于水平标题,非常紧凑:

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

答案 2 :(得分:1)

我根据以前的答案制作了一个可以正常使用的自定义脚本。

将下一个代码复制并粘贴到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))
希望值得!