qtqwidgetoverlappingqvboxlayout

Avoid overlapping of Widgets in QVBoxLayout


I tried to dynamically add more fields to select multiple paths in my application. Unfortunaley I am not able to get rid of the overlap that some icons have:

enter image description here

I add them with the following code:

void SettingsDialog::addPathEdit(QString dir)
{
    if (amountPaths > maxAmountPaths) {
        showError(tr("Cannot add more than %1 paths").arg(maxAmountPaths));
        return;
    }
    QHBoxLayout *hLayout = new QHBoxLayout();
    hLayout->setObjectName("pathLine");
    hLayout->setSizeConstraint(QHBoxLayout::SetMinimumSize);

    QLineEdit *lineEdit = new QLineEdit(dir);
    lineEdit->setMinimumHeight(25);
    lineEdit->setObjectName("path");
    hLayout->addWidget(lineEdit);

    QPushButton *browseButton = new QPushButton(tr("Browse..."));
    browseButton->setMinimumHeight(25);
    browseButton->setObjectName("browseButton");
    hLayout->addWidget(browseButton);
    connect(browseButton, SIGNAL(clicked()), this, SLOT(on_browse_button_clicked()));

    ui->pathHolderLayout->addLayout(hLayout);
    amountPaths++;
}

where pathHolderLayout is a QVBoxLayout.

Any help is appreciated.


Solution

  • Layouts in Qt have a "size constraint" which defines the minimumSize/maximumSize/sizeHint of the layout, depending on the minimumSize/maximumSize/sizeHint of their contents.

    The default size constraint is QLayout::SetDefaultConstraint, defined as "The main widget's minimum size is set to minimumSize(), unless the widget already has a minimum size."

    Your top-level layout (of the dialog) has the default size constraint (in the .ui file), and you set a minimum size for the dialog (in the .ui file), so the constraint effectively does nothing at all.

    To fix your issue you either have to remove the minimum size of the dialog (e.g. select the value of property the .ui editor and click the back arrow), or set the size constraint of the top-level layout to QLayout::SetMinimumSize.