Setting text on a QLabel in a layout, doesn't resize

梦想的初衷 提交于 2019-11-30 11:36:10

Set the vertical sizepolicy of your label to QSizePolicy::Minimum. Then set the sizeconstraint of your dialog's layout to QLayout::SetMinimumSize. This should make your dialog grow so all the content will fit inside of it.

Something like this:

QVBoxLayout *layout = new QVBoxLayout;
layout->setSizeConstraint(QLayout::SetMinimumSize);
this->setLayout(layout);
for(int i = 0; i < 5; i++)
{
    QLabel *label = new QLabel;
    label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
    label->setWordWrap(true);
    label->setText("This is a very long text. This is a very long text. This is a very long text. "
                   "This is a very long text. This is a very long text. This is a very long text. This is a very long text. "
                   "This is a very long text. This is a very long text.");
    layout->addWidget(label);
}

In my experiments, just setting the layoutSizeConstraint property to SetMinimumSize on the layout that contains the QLabel should be enough to let the label expand and adjust to its contents.

You can either change that property in Qt Designer, if you used it to build your UI, or via code:

layout->setSizeConstraint(QLayout::SetMinimumSize);

Note that if you have nested layouts, you may need to set the constraint in all layouts up the chain. No changes to the label's own sizePolicy is needed -- the defaults (Preferred for both the horizontal and vertical size policy) should work, at least in my experience.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!