简体   繁体   English

Label 文本自动拉伸到其父 pyqt5

[英]Label Text automatically stretch to it's parent pyqt5

I am trying to stretch text in label to it's size.我正在尝试将 label 中的文本拉伸到它的大小。

For example, if I increase the height of the label, then the inner text's size should be increased only vertically.例如,如果我增加 label 的高度,那么内部文本的大小只能垂直增加。

If I increase the width of the label, then the inner text's size should be increased and stretched only horizontally.如果我增加 label 的宽度,那么内部文本的大小应该增加并且只能水平拉伸。

How can I do this?我怎样才能做到这一点?

You could use a QPainterPath and a QTransform to deform your text:您可以使用QPainterPathQTransform变形您的文本:

Draw your text in a QPainterPath with a arbritrary font size.在具有任意字体大小的QPainterPath中绘制文本。 Based on the sizes of your widget and your path, you will get the scale factor.根据小部件的大小和路径,您将获得比例因子。 Transform your path, then draw it:变换路径,然后绘制它:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM