Search code examples
c++qtqdockwidget

Automatically resize DockWidgets to same heights after adding a new DockWidget


I'm currently writing a small application, that allows the user to freely define plots. The current solution uses QDockWidget, so that the user can resize and rearrange the plots as he pleases.

I'm quite happy with this solution, but there is still a drawback. In case the user adds a new QDockWidget to the already defined ones a good behavior would be to resize all QDockWidgets to have the same heights.

The following code illustrates what I'm trying to achieve.

#include <QtGui>
#include <QMainWindow>
#include <QDockWidget>
#include <QLabel>
#include <QApplication>
#include <QAction>
#include <QMenuBar>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    auto window = new QMainWindow;
    auto label = new QLabel("Central Widget");
    label->hide();
    window->setCentralWidget(label);
    window->setDockNestingEnabled(true);
    for (int i = 1; i < 3; i++) {
        auto dock = new QDockWidget(QString("Plot %1").arg(i));
        dock->setWidget(new QLabel(QString("Plot %1").arg(i)));
        window->addDockWidget(Qt::LeftDockWidgetArea, dock);
    }
    window->setFixedSize(QSize(300, 600));
    window->show();

    // User presses a button and the following would get executed!
    auto dock = new QDockWidget(QString("New Plot"));
    dock->setWidget(new QLabel(QString("New Plot")));
    window->addDockWidget(Qt::LeftDockWidgetArea, dock);
    return app.exec();
}

Unfortunately, the newly added plot has a very small size, whereas the other two are still large.

Behavior of code

The desired behavior should be something like this, after I manually resized the dock widgets. Desired behavior

How can I achieve this behavior with the least amount of extra work? Do I really have to resize all my QDockWidgets manually?


Solution

  • This is happening because you have not defined any minimum size to the QDockWidgets. So if you want your third dock widget should be of the same size. Set its minimum height to the 1/3rd of the total window size like this:

    dock->setMinimumHeight(window->height()/3); //! This is the third dock widget