首页 > 解决方案 > 标签文本自动拉伸到它的父 pyqt5

问题描述

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

例如,如果我增加标签的高度,那么内部文本的大小应该只垂直增加。

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

我怎样才能做到这一点?

标签: pythontextpyqt5adjustmentqsizepolicy

解决方案


您可以使用 aQPainterPath和 aQTransform变形您的文本:

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)

推荐阅读