该例子介绍如何在正在运行的应用程序中重新布局控件。
mainLayout = new QGridLayout;
mainLayout->addWidget(rotatableGroupBox, 0, 0);
...
setLayout(mainLayout);
rotatableGroupBox = new QGroupBox(tr("Rotatable Widgets"));
rotatableWidgets.enqueue(new QSpinBox);
rotatableWidgets.enqueue(new QSlider);
rotatableWidgets.enqueue(new QDial);
rotatableWidgets.enqueue(new QProgressBar);
...
/* 绑定QGridLayout布局 */
rotatableLayout = new QGridLayout;
rotatableGroupBox->setLayout(rotatableLayout);
rotateWidgets();
Rotate Widgets
时会执行下列函数进行重新布局。void Dialog::rotateWidgets()
{
Q_ASSERT(rotatableWidgets.count() % 2 == 0);
foreach (QWidget *widget, rotatableWidgets)
rotatableLayout->removeWidget(widget); /* 移除旧布局 */
rotatableWidgets.enqueue(rotatableWidgets.dequeue());
const int n = rotatableWidgets.count();
for (int i = 0; i < n / 2; ++i) {
/* 重新布局 */
rotatableLayout->addWidget(rotatableWidgets[n - i - 1], 0, i);
rotatableLayout->addWidget(rotatableWidgets[i], 1, i);
}
}
本文例子中动态布局的主要实现使用了,布局类(QGridLayout)的addWidget和removeWidget操作。
C:\Qt\{你的Qt版本}\Examples\{你的Qt版本}\widgets\layouts\dynamiclayouts
https://doc.qt.io/qt-5/qtwidgets-layouts-dynamiclayouts-example.html