如果你想在动态添加控件后,保持layout->addStretch(1)
占据布局的底部位置,可以将addStretch(1)
放在最后一次添加控件之后。这样新添加的控件会自动向上填充剩余空间。
以下是一个示例代码:
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget window;
QVBoxLayout* layout = new QVBoxLayout(&window);
QPushButton* button1 = new QPushButton("按钮1");
layout->addWidget(button1);
QPushButton* button2 = new QPushButton("按钮2");
layout->addWidget(button2);
// 添加可伸缩的空间,占据额外的垂直空间,并保持在底部
layout->addStretch(1);
QPushButton* button3 = new QPushButton("按钮3");
layout->addWidget(button3);
window.show();
return app.exec();
}
在上述代码中,先添加了两个按钮button1
和button2
,然后使用addStretch(1)
方法添加可伸缩空间,并确保它位于布局的底部。最后再添加一个按钮button3
。这样新添加的控件就会被推到布局顶部,而可伸缩空间仍然会填充剩余的底部空间。
内容由零声教学AI助手提供,问题来源于学员提问