Python 标签文本自动拉伸到它';s父pyqt5

Python 标签文本自动拉伸到它';s父pyqt5,python,text,pyqt5,adjustment,qsizepolicy,Python,Text,Pyqt5,Adjustment,Qsizepolicy,我正在尝试将标签中的文本拉伸到它的大小 例如,如果我增加标签的高度,则内部文本的大小应仅垂直增加 如果我增加标签的宽度,那么内部文本的大小应该增加,并且只能水平拉伸 如何执行此操作?您可以使用QPainterPath和QTransform来变形文本: 使用任意字体大小在QPainterPath中绘制文本。根据小部件和路径的大小,您将获得比例因子。变换路径,然后绘制它: class Widget(QWidget): def __init__(self, parent=None):

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

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

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


如何执行此操作?

您可以使用
QPainterPath
QTransform
来变形文本:

使用任意字体大小在
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)