简体   繁体   中英

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:

启用 wordWrap 的标签

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

没有自动换行的标签

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

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 QSizePolicy s 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM