How to programatically resize a QMainWindow to its minimum size

时光毁灭记忆、已成空白 提交于 2019-12-10 14:04:56

问题


When I have a QMainWindow with a grid layout, when resizing it with the mouse, it won't go below some minimum size that's necessary for all the controls in it to show properly. In my app I sometimes programatically hide controls, but then the window remains the same size and the rest of the controls look spread out, with too much space between them. I end up resizing the dialog manually so it doesn't look ugly.

Can I programatically set the dialog's vertical size to this minimum I get when manually resizing after I've hidden controls in it?


回答1:


I have found that resizing the centralWidget in the QMainWindow then resizing the QMainWindow itself does the trick. In other words:

from PyQt4 import QtGui
class MyMainWindow(QtGui.QMainWindow):
    def __init__(self):
        # define some widgets and stuff
    def whenWidgetsAreHidden(self):
        # this method should be triggered when you hide your widgets
        self.centralWidget.adjustSize()
        self.adjustSize()

Note that there are other widgets in the QMainWindowLayout. Per this image from the Qt Documentation, there are also Dock Widgets and other stuff that could be present. I only use the centralWidget so this solution works for me.




回答2:


There is hierarchy between QLayout::SizeConstraint, QWidget::minimumSizeHint, QWidget::minimumSize, and you can find it in the documentation.

  • QWidget::minimumSize is not set by default. When it is, it prevails over QWidget::minimumSizeHint
  • QWidget::minimumSizeHint is invalid if the widget is not in a layout (meaning that it can be resized to 0 with the mouse), otherwise use the one defined by the layout.
  • QLayout::SizeConstraint holds the default layout behavior of the widgets it *directly * manage. If you nest a layout A within a layout B, all widgets added to A will use its property. Also if a widget W in B define its own layout, then this layout constraints are the one to be applied for the widget W.

Knowing that, follow these steps. It might work, i didn't try :) :

  • Set the minimum size of all widgets you use.
  • Ensure that the size constraint of all your layouts is set to QLayout::SetDefaultConstraint.



回答3:


This code will do the trick (it resizes only the height):

    QWidget widget;
    widget.resize(widget.width(), widget.minimumHeight());


来源:https://stackoverflow.com/questions/8776332/how-to-programatically-resize-a-qmainwindow-to-its-minimum-size

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