布局内容更改后,将QMainWindow调整为最小大小 [英] Resize QMainWindow to minimal size after content of layout changes

查看:147
本文介绍了布局内容更改后,将QMainWindow调整为最小大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用QMainWindow的子类,在其中我声明了一个中央小部件.除其他事项外,此窗口小部件包含QGridLayout,其中包含一组按钮.按钮的数量可以增加或减少,具体取决于用户的输入.间距设置为零,以便所有按钮都聚集在一起.默认情况下,它看起来像这样:

I'm using a subclass of QMainWindow, in which I declared a central widget. This widget contains, among other things, a QGridLayout, which holds a set of buttons. The amount of buttons can grow or shrink, depending on the user's input. The spacing is set to zero, so that all buttons are clumped together. By default, it looks like this:

如果增加按钮的数量,则网格和窗口将增长得恰到好处;但是,如果减少了按钮的数量,它将看起来像这样:

If the amount of buttons is increased, the grid and window will grow too just fine; if, however, the amount of buttons is reduced, it will look like this:

现在,我想调整窗口/布局/小部件的大小,以便所有按钮都可以使用最小的空间.我已经尝试了各种方法,但都无济于事.我查看了 this 和<一个href ="https://stackoverflow.com/questions/7031787/how-to-resize-qmainwindow-after-removing-all-dockwidgets">这个问题,以及Qt板中的各个线程,但是他们都没有为我工作.

Now I would like to resize the window/layout/widget so that all buttons may use the minimal space. I've tried various things, but all to no avail. I had a look at this and this question, as well at various threads in the Qt board, but none of them worked for me.

我的布局如下构建:

self.grid = QtGui.QGridLayout()
self.grid.setSpacing(0)

hBox = QtGui.QHBoxLayout()
hBox.addWidget(...)

vBox = QtGui.QVBoxLayout(self.widget)
vBox.addLayout(hBox)
vBox.addLayout(self.grid)

self.setCentralWidget(self.widget)

我尝试用...调整大小

I tried resizing it with ...

self.widget.layout().activate()
self.resize(self.minimumSize())
# self.resize(self.sizeHint())

...和其他各种方法.我还尝试设置窗口和网格的大小策略.

... and various other methods. I also tried setting the size policy of my window and grid.

推荐答案

更改小部件数量后,您可以将窗口的大小调整为<​​c2>:

You can resize the window to minimumSizeHint() after the number of widgets is changed :

self.resize(minimumSizeHint())

这会将窗口缩小到最小尺寸.但是,您应该考虑到只有在事件循环中处理了一些事件之后,才会计算出最小大小.因此,当更改按钮数量时,只需处理事件循环进行一些迭代,然后将其调整为最小即可.

This will shrink the window to minimum size. But you should consider that the minimum size is not computed until some events are processed in the event loop. So when the number of buttons are changed, just process the event loop for some iterations and then resize to minimum.

就像:

for i in range(0, 10):
      QApplication.processEvents()

self.resize(minimumSizeHint())

另一种选择是单拍一个QTimer,该QTimer会调用一个插槽,您可以在其中将窗口调整为最小尺寸.这样,当您调整窗口大小时,最小大小提示将正确计算.

Another option is to single shot a QTimer which calls a slot in which you resize the window to minimum. This way when you resize the window, the minimum size hint is computed correctly.

这篇关于布局内容更改后,将QMainWindow调整为最小大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆