I want to rotate a QLabel so that it is oriented vertically. A similar question was asked here: PyQT: Rotate a QLabel so that it's positioned diagonally instead of horizontally but the code in answer causes a recursive loop issue.
Here is the code I am using, why does the code run in a recursive loop and why are the labels not drawn?:
from PyQt4.QtGui import QLabel, QPainter
from PyQt4.QtCore import QSize
from PyQt4 import QtCore, QtGui
import sys
class VerticalLabel(QLabel):
def __init__(self, text = ""):
QtGui.QLabel.__init__(self, text)
self.text = text
def paintEvent(self, event):
painter = QPainter(self)
painter.setPen(QtCore.Qt.black)
painter.translate(0, self.height()-1)
painter.rotate(-90)
self.setGeometry(self.x(), self.y(), self.height(), self.width())
painter.drawText(0, 0, self.text)
print("text: {0}".format(self.text))
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())
def setText(self, newText):
self.text = newText
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
lbl1 = VerticalLabel('label 1')
lbl2 = VerticalLabel('label 2')
lbl3 = VerticalLabel('label 3')
hBoxLayout = QtGui.QHBoxLayout()
hBoxLayout.addWidget(lbl1)
hBoxLayout.addWidget(lbl2)
hBoxLayout.addWidget(lbl3)
self.setLayout(hBoxLayout)
self.setGeometry(300, 300, 250, 150)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
This is slightly modified version of the same code from another answer and remember if you put any print under paintEvent it will print every time if you have any activity on the widget like mouse move or re size or what ever even a touch in window will redraw, because that's what paintEvent means.
class MyLabel(QtGui.QWidget):
def __init__(self, text=None):
super(self.__class__, self).__init__()
self.text = text
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.setPen(QtCore.Qt.black)
painter.translate(20, 100)
painter.rotate(-90)
if self.text:
painter.drawText(0, 0, self.text)
painter.end()
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
lbl1 = MyLabel('lbl 1')
lbl2 = MyLabel('lbl 2')
lbl3 = MyLabel('lbl 3')
hBoxLayout = QtGui.QHBoxLayout()
hBoxLayout.addWidget(lbl1)
hBoxLayout.addWidget(lbl2)
hBoxLayout.addWidget(lbl3)
self.setLayout(hBoxLayout)
self.setGeometry(300, 300, 250, 150)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With