1
votes

I would like the text to auto-fit inside of the label. As the width of the QLabel gets more narrow the text formats to occupy multiple lines. Essentially I am looking for a way to format it the same way a html text is formatted when we resize the web browser window.

label=QtGui.QLabel()  

text = "Somewhere over the rainbow Way up high And the dreams that you dreamed of Once in a lullaby"    

label.setText(text)
label.show()
1
Have you tried label.setWordWrap(True)?Frank Osterfeld

1 Answers

0
votes

I have ended up using QLabel's resizeEvent() to get a real-time label's width value which is used to format the label's monofont text on a fly:

enter image description here

text = "Somewhere over the rainbow Way up high And the dreams that you dreamed of Once in a lullaby..."    

class Label(QtGui.QLabel):
    def __init__(self, parent=None):
        super(Label, self).__init__(parent)  

    def resizeEvent(self, event):
        self.formatText()
        event.accept()

    def formatText(self):
        width = self.width()
        text = self.text()
        new = ''
        for word in text.split():
            if len(new.split('\n')[-1])<width*0.1:
                new = new + ' ' + word
            else:
                new = new + '\n' + ' ' + word
        self.setText(new)

myLabel = Label()
myLabel.setText(text)
myLabel.resize(300, 50)
font = QtGui.QFont("Courier New", 10)
font.setStyleHint(QtGui.QFont.TypeWriter)
myLabel.setFont(font)
myLabel.formatText()
myLabel.show()