qtqlabelqtwidgetsqsizepolicy

How to prevent a QLabel from expanding because of added text?


There is a QLabel added to the status bar of the main window. When setting a long text, the QLabel expands and expands the window with it. It is necessary that the size of the QLabel and the window do not change, and only the text that fits is shown (as happens with a fixed size widget).

The width of the QLabel cannot be fixed, because it must change depending on the width of the window. Probably there are some size policy settings for widgets?

I tried setting a fixed width and different size policies.


Solution

  • Use QSizePolicy::Ignored for the label's width, and set its stretch factor to 1 in the layout:

    statusTextLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::MinimumExpanding);
    
    ui->statusbar->addWidget(statusTextLabel, 1); //stretch must be set