pythontextpyqt5adjustmentqsizepolicy

Label Text automatically stretch to it's parent pyqt5


I am trying to stretch text in label to it's size.

For example, if I increase the height of the label, then the inner text's size should be increased only vertically.

If I increase the width of the label, then the inner text's size should be increased and stretched only horizontally.

How can I do this?


Solution

  • You could use a QPainterPath and a QTransform to deform your text:

    Draw your text in a QPainterPath with a arbritrary font size. 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)