PyQT: Rotate a QLabel so that it's positioned

2019-02-15 12:05发布

问题:

I'm working on a touch screen app where gui space is very tight. I'd like to rotate a QLabel a bit so that it's either vertical, or offset at a diagonal a bit. Any suggestions? I couldn't find anything relevant on the QLabel interface.

Thanks so much!

回答1:

QLabel does not do this. But you can easily create your own widget containing a bit of text:

class MyLabel(QtGui.QWidget):
    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setPen(QtCore.Qt.black)
        painter.translate(20, 100)
        painter.rotate(-90)
        painter.drawText(0, 0, "hellos")
        painter.end()

Another option is to draw a QGraphicsView, you then have the liberty to map real widgets (i.e. a QLabel) through any coordinate transformation.



回答2:

I used this post to make another solution that I think is maybe better. Here it is:

class VerticalLabel(QLabel):

    def __init__(self, *args):
        QLabel.__init__(self, *args)

    def paintEvent(self, event):
        QLabel.paintEvent(self, event)
        painter = QPainter (self)
        painter.translate(0, self.height()-1)
        painter.rotate(-90)
        self.setGeometry(self.x(), self.y(), self.height(), self.width())
        QLabel.render(self, painter)

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