Important: Please read the Qt Code of Conduct -

Problem with layout of QDockWidgets

  • Hello,

    I have a QMainWindow application where I can load several composition of sub windows (QDockWidgets). I made a small Demo to show my problem.
    Question: Why does the layout change when I press the 'Open' action. In the beginning both Widgets have the same width. After 'Open' the left widget has higher width compared to the right one.

    Thanks a lot,

    #include <QMainWindow>

    class Demo: public QMainWindow {
    public slots:
    void OnOpen();

    #include <QApplication>
    #include <QDockWidget>
    #include <QToolBar>
    #include <QAction>
    #include "Demo.h"

    int main(int argc, char **argv) {
    QApplication App(argc,argv);
    Demo D;
    return App.exec();

    Demo::Demo() {
    QToolBar *TB = new QToolBar(this);
    QAction *Open = new QAction("Open", this);
    connect(Open,SIGNAL(triggered()), this, SLOT(OnOpen()));

    void Demo::OnOpen() {
    QList<QDockWidget *> DWL = findChildren<QDockWidget *>();
    for (int i=0; i<DWL.size(); i++) {
    QDockWidget *DW;
    DW = new QDockWidget("DW 1");
    DW = new QDockWidget("DW 2");

  • Moderators

    It's because the first time you call OnOpen() your main window is not shown yet.

    In that scenario you add two docks to invisible window, so the layout manager doesn't bother to calculate the sizes.
    When you show the window it goes "oh, there are two docks that don't have sizes yet. They have same size policies so I'll better split the available space between them equally."

    When you call OnOpen() second time something entirely different is happening.
    The window is visible, so when you add first dock the layout manager goes "oh, there's no other widget here so I'll just give all available space to that new dock.
    Then you add another one so the layout manager says "gosh, this new dock has a minimum size(because of the title bar) but I don't have any room for it. Oh ok, I'll just shrink a little this other dock that's there so I can fit this new one."

    To observe that better switch

  • Thanks so far.
    At least it is the same situation in both cases now (width of left widget is heigher than of right widget).

    BUT: how can a achieve that the Widgets have the same width?

    Thanks again,

  • Moderators

    A quick and dirty way would be to call hide() before adding dock widgets and show() afterwards, but it has an ugly flicker to it.
    There should be another way to prevent layout manager from kicking in too soon, but I just can't think of any right now.

  • Thanks Chris,

    your first answer was good for me in the sense that I have deterministic behaviour right now.
    I am already reading about size policies. Seems to be problematic in Qt since there are no layouts or similar for QDockWidgets. But I can figure this out.

    Thanks again,

Log in to reply