1

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dauren slambekov
  • 378
  • 3
  • 15

1 Answers1

2

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)
Dimitry Ernot
  • 6,256
  • 2
  • 25
  • 37