0
votes

I have a hidden widget in my dialog. When I show it, I want the dialog window to expand accordingly and shrink again when I choose to hide it.

How can this be done? I have tried understanding the layout functionality of Qt but I find it very hard to grasp.

2
this might be helpful: resize-window-to-fit-contentsongziming

2 Answers

1
votes

Not sure if there is a build-in solution, but this is my manual one:

Dialog::Dialog(QWidget *parent) :
    QDialog(parent)
{
    setupUi(this);

    connect(toolButton, SIGNAL(toggled(bool)), SLOT(onToolButton(bool)));

    onToolButton(false);
}

void Dialog::onToolButton(bool checked)
{
    lineEdit->setVisible(checked);

    int maxHeight = verticalLayout->contentsMargins().top()
            + verticalLayout->contentsMargins().bottom();
    int itemsCount = 0;
    for (int i = 0; i < verticalLayout->count(); ++i) {
        QLayoutItem *item = verticalLayout->itemAt(i);
        if (item->widget()) {
            QWidget *w = item->widget();
            if (w->isVisible()) {
                maxHeight += w->geometry().height();
                ++itemsCount;
            }
        } else if (item->layout()) {
            QLayout *l = item->layout();
            maxHeight += l->geometry().height();
            ++itemsCount;
        }
    }
    if (itemsCount > 1)
        maxHeight += ((itemsCount - 1) * verticalLayout->spacing());

    setMaximumHeight(maxHeight);
}
1
votes

Try use QWidget::adjustSize() for container after show/hide content.