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,
ThomasDemo.h
@
#include <QMainWindow>class Demo: public QMainWindow {
Q_OBJECT
public:
Demo();
public slots:
void OnOpen();
};
@Demo.cpp
@
#include <QApplication>
#include <QDockWidget>
#include <QToolBar>
#include <QAction>
#include "Demo.h"int main(int argc, char **argv) {
QApplication App(argc,argv);
Demo D;
D.OnOpen();
D.show();
return App.exec();
}Demo::Demo() {
resize(500,300);
QToolBar *TB = new QToolBar(this);
addToolBar(TB);
QAction *Open = new QAction("Open", this);
connect(Open,SIGNAL(triggered()), this, SLOT(OnOpen()));
TB->addAction(Open);
}void Demo::OnOpen() {
QList<QDockWidget *> DWL = findChildren<QDockWidget *>();
for (int i=0; i<DWL.size(); i++) {
removeDockWidget(DWL.at(i));
delete DWL.at(i);
}
QDockWidget *DW;
DW = new QDockWidget("DW 1");
addDockWidget(Qt::LeftDockWidgetArea,DW,Qt::Horizontal);
DW = new QDockWidget("DW 2");
addDockWidget(Qt::LeftDockWidgetArea,DW,Qt::Horizontal);
}
@ -
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
@
D.OnOpen();
D.show();
@
to
@
D.show();
D.OnOpen();
@ -
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,
Thomas