Nominate our 2022 Qt Champions!

Having QLabels resize outside a layout

  • I have some QLabels which I don't want to put in a layout, so I can set their positions pixel-by-pixel. They have some text, which I want to be able to change later.

    Whenever I call setText() on one of them after-the-fact, changing the contents, the width of the label stays the same as it was for the old string. I have to call resize() and update() to update the size. However, I have to either guess at this new size or calculate it based on the font metrics, which is far from ideal.

    If I put the QLabels in a layout, they resize automatically when I call setText(). Is there a way to make them do that from outside a layout?

  • I am not sure if this will help you, but I had a similar problem with QLabels regarding move() operations. What worked for me was to show() them after setText() (even if they were already visible).

    I am not 100% sure, but I believe it might be related to the following (from the QWidget documentation for visible()):

    "...If its size or position has changed, Qt guarantees that a widget gets move and resize events just before it is shown. If the widget has not been resized yet, Qt will adjust the widget's size to a useful default using adjustSize()..."

  • Hi,
    Since you place them outside a layout, you, and you alone, are responsible for resize operations. How should Qt be able to do so if it doesn't know how to resize (layout operation). Maybe with the textChanged signal do a calculation based on the font and string or call the resize and update.

Log in to reply