Search code examples
qtlayoutresize

How to detect if a qt label (or any widget) has all the space it would need?


My widget has a long label in a gridlayout which, whithout any extra line of code, inhibits shrinking the window. In this post I saw that setting label1.setMiniumSize(1, 1) enables shrinking of the window again. However, I would like to display an abbreviated form of the text in the label if shrinking the windows cuts the display of the text.

Here is an example:

  1. Starting point: label1.setText("This is a long long long long long long long long label") displays "This is a long long long long long long long long label" and inhibits shrinking of the window.

  2. After adding label1.setMinimumSize(1, 1) the window can be shrunk and it displays "This is a long lo"

  3. I would like to have the display of "This is ... ong label" or "This is a long ... long label", adapted to the really available size for the label.

Can we catch the information what size the layout manager would like to give to the label? Calculate the number of characters that correspond, Abbreviate the text, And set the new text?


Solution

  • You can use QFontMetricsF to get the size of the QLabel required to draw the text. Inversely, you can override the resizeEvent() of QLabel to get the current size of the label every time it changes size and adapt your text to it.

    QFontMetricsF FM(ui->label->font());
    QRectF rect = FM.boundingRect("A Long Long Long Long Text");
    double rectWidth = rect.width();
    if (rectWidth > ui->label->width())
    {
        // Change text and recalculate in a loop if it fits
    }
    

    The best place to do it would be in resizeEvent() of either the label or the parent widget.