Prevent QDockWidget autosizing behaviour

天涯浪子 提交于 2019-12-10 15:54:46

问题


Qt 5.5.0

In my application, I have a QGraphicsView as the main widget and a QDockWidget for properties. The goal is for the user to select an item in the graphics view and, depending on the item, present the appropriate properties for that item.

I achieve this by having a properties manager widget with a layout containing each of the properties widgets. I have signals and slots hooked up for getting the currently selected item, and then show() the widget I need and hide() the rest.

This works great! However, when selecting different items, the dock shrinks or grows based on the shown widget. It is very jarring, and rather annoying. The thing is though, that when the user manually resizes the dock, it maintains that size. I want the maintained size to be default rather than this autosizing behaviour.


Things I've tried:

I've tried changing the sizePolicy() of the dock and the mainwindow: No effect.

I've set a minimum size for my properties manager which does indeed prevent the dock from shrinking when a smaller set of properties is shown. However, I still want the user to be able to shrink the dock to a smaller size if they wish, and this method prevents that...


Conclusion:

Is there a flag or something that is set when the user resizes the dock that tells it to maintain that size? If so, is there a way to manually set it?

I haven't tried subclassing QDockWidget or QMainWindow yet. Is there a method(s) that I can override to achieve the correct behaviour?

Thanks for any help!


回答1:


All that was necessary was to call

setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);

in the constructor of my properties manager widget (the central widget of the QDockWidget)

I also overloaded the sizeHint() function to return a respectable default size.




回答2:


First, create your dock widget:

QDockWidget *dock = new QDockWidget;

Now set size policy to dock's widget.

If dock is vertical:

dock->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Expanding);

If dock is horizontal:

dock->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Ignored);

Set your widget to dock:

QWidget *myWidget = new QWidget;
dock->setWidget(myWidget);

Now set size policy to dock's widget.

If dock is vertical:

dock->widget()->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Expanding);

If dock is horizontal:

dock->widget()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Ignored);

Finally, add dock to main window:

If dock is vertical:

mainWindow->addDockWidget(Qt::LeftDockWidgetArea, dock);
mainWindow->resizeDocks({dock}, {0}, Qt::Horizontal);

If dock is horizontal:

mainWindow->addDockWidget(Qt::TopDockWidgetArea, dock);
mainWindow->resizeDocks({dock}, {0}, Qt::Vertical);


来源:https://stackoverflow.com/questions/34553069/prevent-qdockwidget-autosizing-behaviour

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!