To display the Y axis title of an image I needed a vertical label. But how do you rotate the text in a QLabel?

By merging inputs from several sources on the Internet, I ended up writing this helper class called VLabel. The name implies that it is just a vertical variation on a normal QLabel, from which it actually inherits. I would have preferred a shorter solution but this is the simplest which I could write that actually just works.

The following is Python code using PyQt5, translation for Qt4 and other languages should be pretty straightforward.

You can use VLabel just as you would use QLabel.

from PyQt5.QtWidgets import QLabel
from PyQt5.QtGui import QPainter
from PyQt5.QtCore import Qt, QSize

class VLabel(QLabel):
    def __init__(self, *args):
        QLabel.__init__(self, *args)
        QLabel.show(self)  # needed so the QLabel can calculate its width
        self.setFixedSize(QLabel.size(self).width(), QLabel.size(self).height())

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setPen(Qt.black)
        # 15 is a hardcoded value, may need corrections depending on font size
        painter.translate(15, self.size().height()-1)
        painter.rotate(-90)
        painter.drawText(0, 0, QLabel.text(self))
        painter.end()

    def minimumSizeHint(self):
        size = QLabel.minimumSizeHint(self)
        return QSize(size.height(), size.width())

    def sizeHint(self):
        size = QLabel.sizeHint(self)
        return QSize(size.height(), size.width())