QT Flowlayout - issue with multiline labels

折月煮酒 提交于 2019-12-24 08:42:09

问题


I have a small problem with QT layout.

I have a toolbox, and I want to populate it with some checkable buttons with a description. So I create a QWidget with a QGridLayout and put the QButton in the first cell and the QLabel in the second.

This is the most important part of the code (I removed dependancies from other irrelevant code in the app):

QWidget *createCellWidget()
{
    QToolButton *button = new QToolButton(this);
    button->setCheckable(true);
    button->setMinimumSize(57,57);
    button->setMaximumSize(57,57);

    QWidget *widget = new QWidget(this);
    QGridLayout *layout = new QGridLayout(widget);
    layout->addWidget(button, 0, 0, Qt::AlignHCenter);
    QLabel *lbl = new QLabel("my very long caption");
    lbl->setWordWrap(true);
    lbl->setAlignment(Qt::AlignCenter);

    layout->addWidget(lbl, 1, 0, Qt::AlignTop);
    widget->setMaximumWidth(80);
    widget->setMinimumWidth(80);

    return widget;
}

then I create a QGridLayout and populate it with these controls:

QWidget *itemWidget_FlowControl = new QWidget(this);
QGridLayout *_flowControl_layout = new QGridLayout(itemWidget_FlowControl);
_flowControl_layout->addWidget(createCellWidget(), 0, 0);

This works well and produces this output:

this is a nice layout. Unluckily if I enlarge the window the controls do not "flow", so I tried to replace the QGridLayout with a flowlayout (here are the source files).

Now the behavior is much better. BUT...

this is what I get. The longer captions are laid out as if they were single-lined, so the text overlaps with the button.

What can I do to make it look like before, but keeping it as a "flow layout"? Or do you know if there is any alternative in QT 5.2?

Thank you


回答1:


What's wrong?

You are on the right track of using flowlayout.

The only problem is the internal layouts (QGridLayout in your case) of your cell widgets also stretch in response to the resize events.


Solution

The solution is surprisingly simple:

Try to limit the stretch of the internal layout.

Within the factory function QWidget *createCellWidget():

[Option 1]

Add lbl->setMaximumWidth(60); to manually limit the stretch of label width. This makes the internal layout not stretch so "freely."

[Option 2]

Add layout->setSizeConstraint(QLayout::SetFixedSize); to restrain the internal layout stretch. By doing this, you may want to manually add some line break code (\n) to your "very long caption" in case the label width automatically decided by Qt doesn't suit your need.


Result




回答2:


IMO the best approach would be use off style sheets (flow layout is Ok). Simply use QButton but customize its view by altering its stye sheet.
Currently I have no time to write an example.



来源:https://stackoverflow.com/questions/29237206/qt-flowlayout-issue-with-multiline-labels

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