【发布时间】:2015-05-28 11:44:02
【问题描述】:
我的对话框中有一个隐藏的小部件。当我显示它时,我希望对话框窗口相应地展开并在我选择隐藏它时再次缩小。
如何做到这一点?我尝试了解 Qt 的布局功能,但我发现很难掌握。
【问题讨论】:
-
这可能会有所帮助:resize-window-to-fit-content
我的对话框中有一个隐藏的小部件。当我显示它时,我希望对话框窗口相应地展开并在我选择隐藏它时再次缩小。
如何做到这一点?我尝试了解 Qt 的布局功能,但我发现很难掌握。
【问题讨论】:
在显示/隐藏内容后尝试对容器使用 QWidget::adjustSize()。
【讨论】:
不确定是否有内置解决方案,但这是我的手动解决方案:
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);
}
【讨论】: