I have many narrow columns with very long labels. I want to rotate the labels by 90 degrees. Is it possible?
3 Answers
You will probably have to subclass QTableWidgetItem and implement your own vertical text painting. Then use setHorizontalHeaderItem()
on your table to point to an instance of your new widget.

- 21,942
- 7
- 74
- 67
When searching for an answer to this questions I found many hints, but no real answer. The hints tell one to subclass QHeaderView and re-implement paintSection. When I tried to do so in PyQt4 and tried to implement paintSection from scratch, following the source of QHeaderView, I was not successful. However, simply rotating the painter instance and adjusting all the size hints was successful. The code works for horizontal headers only and is nicely compact:
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

- 543
- 1
- 5
- 13
I've made a custom script that works fine based on previous answer..
copy and paste the next code in a rotated.py file
#!/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
then import from your main.py file this class using this line:
from rotated import RotatedHeaderView
and complete the actions with this line:
self.YourTableName.setHorizontalHeader(RotatedHeaderView(self.YourTableName))
hope worth it!

- 21
- 1