#include #include #include class ContentWidget : public QWidget { public: ContentWidget(QWidget* parent = 0) : QWidget(parent) {} protected: void paintEvent(QPaintEvent *event) override { QPainter painter(this); painter.save(); QRect rect = geometry(); QRect local = QRect(mapFromParent(rect.topLeft()), mapFromParent(rect.bottomRight())); painter.setPen(QPen(QColor(255, 0, 0, 255), 1.0f, Qt::SolidLine)); painter.drawRect(local.left(), local.top(), local.width() - 1, local.height() - 1); painter.fillRect(local, QColor(255, 0, 0, 10)); if (testAttribute(Qt::WA_NativeWindow)) { const HWND hwnd = (HWND)winId(); if (IsWindow(hwnd)) { RECT wndRect; GetWindowRect(hwnd, &wndRect); QRect wndLocal = QRect(mapFromGlobal({ wndRect.left, wndRect.top }), mapFromGlobal({ wndRect.right, wndRect.bottom })); painter.setPen(QPen(QColor(0, 255, 0, 255), 1.0f, Qt::DotLine)); painter.drawRect(local.left(), local.top(), local.width() - 1, local.height() - 1); painter.fillRect(local, QColor(0, 255, 0, 10)); } } painter.restore(); } void resizeEvent(QResizeEvent *event) override { QWidget::resizeEvent(event); } }; int main(int argc, char *argv[]) { QApplication a(argc, argv); QMainWindow mainWindow; mainWindow.resize(300, 300); mainWindow.setMenuBar(new QMenuBar); auto contatinerWidget = new QWidget; { auto layout = new QBoxLayout(QBoxLayout::TopToBottom); contatinerWidget->setLayout(layout); } auto rootSplitter = new QSplitter(Qt::Horizontal, contatinerWidget); rootSplitter->setChildrenCollapsible(false); contatinerWidget->layout()->addWidget(rootSplitter); mainWindow.setCentralWidget(contatinerWidget); auto areaWidget = new QWidget(contatinerWidget); { auto layout = new QBoxLayout(QBoxLayout::TopToBottom); areaWidget->setLayout(layout); } auto contentWidget = new ContentWidget; contentWidget->setAttribute(Qt::WA_NativeWindow, true); contentWidget->setParent(nullptr); areaWidget->layout()->addWidget(contentWidget); rootSplitter->addWidget(areaWidget); if (QAction* resetLayout = mainWindow.menuBar()->addAction("Reset")) { mainWindow.addAction(resetLayout); QObject::connect(resetLayout, &QAction::triggered, [&]() { if (areaWidget) { auto item = areaWidget->layout()->takeAt(0); assert(item); contentWidget->setParent(nullptr); areaWidget->setParent(nullptr); areaWidget->deleteLater(); areaWidget = nullptr; } if (!areaWidget) { areaWidget = new QWidget(contatinerWidget); auto layout = new QBoxLayout(QBoxLayout::TopToBottom); areaWidget->setLayout(layout); #define LAYOUT_BUG #ifdef LAYOUT_BUG areaWidget->layout()->addWidget(contentWidget); rootSplitter->addWidget(areaWidget); #else rootSplitter->addWidget(areaWidget); areaWidget->layout()->addWidget(contentWidget); #endif } }); } mainWindow.show(); return a.exec(); }