它应该自然工作,所以你做错了什么。小部件上的布局的默认sizeConstraint
仅在小部件太小时增长。您可以将其更改为增大和缩小小部件。
您必须将新的小部件添加到布局中。
您的主窗口中不能有minimumSize()
。如果您从返回非零值的小部件派生,则必须覆盖它并返回零大小。
您不必在delete
之前隐藏子窗口小部件。没有用。只需删除它们,Qt就可以正确处理它。
请参阅下面的完整示例。在OS X和Windows XP + MSVC上测试。
//main.cpp
#include <cstdlib>
#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QHBoxLayout>
#include <QPushButton>
static int pick() { const int N = 10; return (qrand()/N) * N/(RAND_MAX/N); }
class Window : public QWidget {
Q_OBJECT
QLayout * layout;
public:
Window() {
layout = new QHBoxLayout;
QPushButton * button;
button = new QPushButton("Randomize", this);
connect(button, SIGNAL(clicked()), SLOT(randomize()));
layout->addWidget(button);
button = new QPushButton("Grow", this);
button->setCheckable(true);
connect(button, SIGNAL(toggled(bool)), SLOT(grow(bool)));
layout->addWidget(button);
setLayout(layout);
}
private slots:
void randomize() {
// remove old labels
foreach (QObject * o, findChildren<QLabel*>()) { delete o; }
// add some new labels
int N = pick();
while (N--) {
layout->addWidget(new QLabel(QString(pick(), 'a' + pick()), this));
}
}
void grow(bool shrink)
{
QPushButton * button = qobject_cast<QPushButton*>(sender());
if (shrink) {
button->setText("Grow && Shrink");
layout->setSizeConstraint(QLayout::SetFixedSize);
} else {
button->setText("Grow");
layout->setSizeConstraint(QLayout::SetDefaultConstraint);
}
}
};
int main(int c, char ** v)
{
QApplication app(c,v);
Window w;
w.show();
return app.exec();
}
#include "main.moc"
为什么你所期望的主窗口,当你告诉子控件调整大小,你告诉它这样做呢? – cmannett85