根据内容自动调整窗口大小 [英] Automatically resizing a window based on its contents

查看:109
本文介绍了根据内容自动调整窗口大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QDialog 子类,它包含一个间隔作为其唯一的直接子类;窗口的所有 UI 元素都包含在间隔器中.用户无法直接更改窗口大小,但当用户与窗口交互时,UI 元素将显示或隐藏.我希望每次发生这种情况时都调整对话框的大小,以便间隔器(和对话框本身)始终占用尽可能少的空间.如何配置我的对话框和我的间隔器以获得所需的行为?

I have a QDialog subclass that contains a spacer as its only immediate child; all of the window’s UI elements are contained in the spacer. The user cannot change the window size directly, but UI elements will be shown or hidden as the user interacts with the window. I’d like the dialog to resize each time this happens so that the spacer (and the dialog itself) always takes up the minimum possible amount of space. How can I configure my dialog and my spacer to get the desired behavior?

(这个问题处理了类似的问题,尽管在这种情况下用户是能够调整窗口大小.我也不清楚 OP 在这种情况下最终做了什么.)

(This question dealt with something similar, although in that case the user was able to resize the window. It was also not clear to me what the OP actually ended up doing in that case.)

推荐答案

你可以在widget数量改变后将窗口大小调整为<​​code>minimumSizeHint() :

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

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 after some widgets are hidden and some other are shown, just process the event loop for some iterations and then resize to minimum.

就像:

for(int i=0;i<10;i++)
   qApp->processEvents();

resize(minimumSizeHint());

更好的解决方案是单次触发 QTimer 调用一个插槽,您可以在其中将窗口大小调整为最小.这样,当您调整窗口大小时,将正确计算最小大小提示.

A better solution 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.

这篇关于根据内容自动调整窗口大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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