我想旋转一个QLabel,使其垂直定向。这里提出了类似的问题:PyQT: Rotate a QLabel so that it's positioned diagonally instead of horizontally但是答案中的代码会导致递归循环问题。
这是我正在使用的代码,为什么代码在递归循环中运行,为什么没有绘制标签?:
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()
答案 0 :(得分:3)
这是来自另一个答案的相同代码的略微修改版本并记住,如果您在paintEvent下放置任何打印,如果您在窗口小部件上有任何活动(如鼠标移动或重新调整大小或甚至触摸),它将每次打印窗口将重绘,因为这就是paintEvent的含义。
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()