标签文本自动拉伸到它的父 pyqt5



我正在尝试将标签中的文本拉伸到它的大小。

例如,如果我增加标签的高度,则内部文本的大小应仅垂直增加。

如果我增加标签的宽度,那么内部文本的大小应该增加并仅水平拉伸。

我该怎么做?

您可以使用QPainterPathQTransform变形文本:

在具有 arbritrary 字体大小的QPainterPath中绘制文本。根据微件的大小和路径,您将获得比例因子。改变你的路径,然后绘制它:

class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.text = "foobar"
def paintEvent(self, event):
super().paintEvent(event)
painter = QPainter(self)
textPath = QPainterPath()
textPath.addText(QPointF(0, 0), painter.font(), self.text)
size = textPath.boundingRect()
scaleX = self.width() / size.width()
scaleY = self.height() / size.height()
transformation = QTransform()
transformation.scale(scaleX, scaleY)
textPath = transformation.map(textPath) # the text will be resized
textPath.translate(0, textPath.boundingRect().height()) # path needs to be "recentered" after transformation
painter.drawPath(textPath)

最新更新