效果:
关键代码:
1、删除主窗口,使用QDockWidget替代主窗口
QWidget* p = takeCentralWidget();
if (p)
delete p;
setDockNestingEnabled(true);
centralWidget = new QDockWidget(this);
centralWidget->setAllowedAreas(Qt::AllDockWidgetAreas);
setCentralWidget(centralWidget);
2、禁止QDockWidget之间互相tab叠加:
//取消AllowTabbedDocks
setDockOptions(QMainWindow::AnimatedDocks);
3、动态插入,根据数量决定初次摆放的位置
Qt::DockWidgetArea area_ = Qt::LeftDockWidgetArea;
if (dockWidgets.size() % 4 == 0)
area_ = Qt::LeftDockWidgetArea;
else if (dockWidgets.size() % 4 == 1)
area_ = Qt::RightDockWidgetArea;
else if (dockWidgets.size() % 4 == 2)
area_ = Qt::TopDockWidgetArea;
else if (dockWidgets.size() % 4 == 3)
area_ = Qt::BottomDockWidgetArea;
QDockWidget *dockWidget = new QDockWidget(this);
dockWidget->setAllowedAreas(Qt::AllDockWidgetAreas);
OneSensorRealtimeViewWindow* dockWidgetContents = new OneSensorRealtimeViewWindow();
dockWidget->setWidget(dockWidgetContents);
dockWidget->setWindowTitle(tr("SN:") + sn + tr(" address:") + add);
this->addDockWidget(area_, dockWidget);
4、当窗口被关闭或者拖动到外部时,进行复位
QDockWidget * last_ = nullptr;
QMapIterator<QString, QDockWidget *> i(dockWidgets);
while (i.hasNext()) {
i.next();
if (i.value() != nullptr)
{
i.value()->show();
i.value()->setFloating(false);
}
}