它应该自然起作用,所以你做错了什么。小部件上的默认sizeConstraint
布局是仅在小部件太小时时才增加小部件。您可以将其更改为增大和缩小小部件。
您必须将新小部件添加到布局中。
您的主窗口不能有minimumSize()
. 如果您从确实返回非零的小部件派生,则minimumSize()
必须覆盖它并返回零大小。
您不必在delete
ing 之前隐藏子小部件。这是毫无意义。只需删除它们,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"