0
votes

I'm trying to make a QLabel Widget that will resize the font of the text so the entire text will always fit in the QLabel.

class QLabelFontAutoResize(QLabel):
    def __init__(self, text):
        super(QLabelFontAutoResize, self).__init__()
        self._text = text
        self.setText(self._text)

    def setText(self, text):
        width     = float( self.size().width() )
        _font     = self.font()
        _fontSize = 1

        #Find Correct Font Size
        while (True):
            _font.setPointSize(_fontSize)
            _fontMetric = QFontMetrics( _font )

            #Text width exceeds QLabel width
            if _fontMetric.width(text) > width:
                _fontSize = _fontSize-1
                break
            _fontSize = _fontSize + 1

        _font.setPointSize(_fontSize)
        self.setFont(_font)

        #This is recursive, How do I actually set the Text
        self.setText(text)

How do I override the setText() without creating a recursive function, and actually set the text of the QLabel?

Note: The QLabel will be a fixed size, and will not resize, so I'm not overriding resizeEvent. I want the font to change when I set the text.

1
super().setText(text)furas

1 Answers

0
votes

You just have to call the parent's method:

class QLabelFontAutoResize(QLabel):
    [...]
    def setText(self, text):
        [...]
        self.setFont(_font)
        QLabel.setText(self, text)
        # super(QLabelFontAutoResize, self).setText(text)
        # super().setText(text)