c++qtqlabelqvboxlayoutqsizepolicy

Vertical size of a QLabel with wordWrap enabled


I have a QLabel in a QVBoxLayout. Most of the times, it only has one line of text, but sometimes, the text can be too long to fit in one line. So I have to enable wordWrap.

I want the label to be as (vertically) small as possible, thus I set setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Maximum).

Now, if there's enough vertical space, the label is higher as it would have to be with only one line:

label with wordWrap enabled

At the same window size and without wordWrap being enabled, the label only takes the minimum space I would like it to take:

label without wordWrap

Can this also be achieved with wordWrap being enabled and independent of the window height?


Solution

  • I tried to reproduce the behavior with a small example. Maybe this might help you to solve your issue. Just enlarge the widget and type some random text having several words separated by white spaces.

    The idea is to use the correct combination of QSizePolicys not just for the QLabel, but also for the other GUI elements.

    #include <QFrame>
    #include <QLabel>
    #include <QGroupBox>
    #include <QLineEdit>
    #include <QHBoxLayout>
    #include <QPushButton>
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        auto frame = new QFrame();
        frame->setLayout(new QVBoxLayout());
        auto groupEdit = new QGroupBox();
        groupEdit->setLayout(new QHBoxLayout());
        auto edit = new QLineEdit();    
        groupEdit->layout()->addWidget(edit);
        frame->layout()->addWidget(groupEdit);
        auto group = new QGroupBox();
        frame->layout()->addWidget(group);
        group->setLayout(new QHBoxLayout());
        auto label = new QLabel();
        groupEdit->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
        group->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
        group->layout()->addWidget(label);
        group->layout()->addWidget(new QPushButton());
        QObject::connect(edit, &QLineEdit::textEdited, [&](const QString& text) {
            label->setText(text);
            label->setWordWrap(true);
        });
        frame->show();
        return a.exec();
    }