C++ 如何设置 QComboBox 宽度以适合最大的项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3151798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I set the QComboBox width to fit the largest item?
提问by Linoliumz
I have a QComboBox
that I fill with QString
using:
我有一个QComboBox
我填充的QString
使用:
comboBox->addItem(someString);
When I start my GUI application the width of the QComboBox
is always 70, even if the smallest item is much larger. How can I dynamically set the width of a QComboBox
, for instance, to the largest QString
within the comboBox
?
当我启动我的 GUI 应用程序时,它的宽度QComboBox
总是 70,即使最小的项目要大得多。如何动态设置的宽度QComboBox
,例如,在最大QString
范围内的comboBox
?
Edit:
编辑:
After some further testing I found the following solution:
经过一些进一步的测试,我找到了以下解决方案:
// get the minimum width that fits the largest item.
int width = ui->sieveSizeComboBox->minimumSizeHint().width();
// set the ComboBoxe to that width.
ui->sieveSizeComboBox->setMinimumWidth(width);
回答by rubenvb
Qt (4.6) online documentation has this to say about QComboBox
:
Qt (4.6) 在线文档有这样的说法QComboBox
:
enum SizeAdjustPolicy { AdjustToContents, AdjustToContentsOnFirstShow, AdjustToMinimumContentsLength, AdjustToMinimumContentsLengthWithIcon }
I would suggest
我会建议
ensuring the
SizeAdjustPolicy
is actually being usedsetting the enum to
AdjustToContents
. As you mention a.ui
file I suggest doing that in Designer. Normally there shouldn't be anything fancy in your constructor at all concerning things you do in Designer.
确保
SizeAdjustPolicy
实际使用将枚举设置为
AdjustToContents
. 当你提到一个.ui
文件时,我建议在 Designer 中这样做。通常,关于您在 Designer 中所做的事情,您的构造函数中根本不应该有任何花哨的东西。
回答by Troubadour
According to the docsthe default SizeAdjustPolicy
is AdjustToContentsOnFirstShow
so perhaps you are showing it and then populating it?
根据文档,默认值SizeAdjustPolicy
是AdjustToContentsOnFirstShow
这样,也许您正在显示它然后填充它?
Either populate it first before showing it or try setting the policy to QComboBox::AdjustToContents
.
在显示之前先填充它,或者尝试将策略设置为QComboBox::AdjustToContents
.
Edit:
编辑:
BTW I'm assuming that you have the QComboBox
in a suitable layout, eg. QHBoxLayout
, so that the size hint/policy is actually being used.
顺便说一句,我假设您有QComboBox
合适的布局,例如。QHBoxLayout
,以便实际使用大小提示/策略。
回答by Dr ALOUI
I was searching for a solution to only change the size of the dropdown menu of the combobox to fit the largest text without changing the size of the combobox itself.
我正在寻找一种解决方案,只更改组合框下拉菜单的大小以适应最大的文本,而不更改组合框本身的大小。
Your suggestion (@Linoliumz) did help me find the solution. Here it is : Suppose you have a combobox called cb:
您的建议 (@Linoliumz) 确实帮助我找到了解决方案。这是:假设您有一个名为 cb 的组合框:
C++:
C++:
width = cb->minimumSizeHint().width()
cb->view().setMinimumWidth(width)
PyQT :
PyQT :
width = cb.minimumSizeHint().width()
cb.view().setMinimumWidth(width)