How do I set the QComboBox width to fit the largest item?

I have a QComboBox that I fill with QString using:


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?


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.


Qt (4.6) online documentation has this to say about QComboBox:

enum    SizeAdjustPolicy  { AdjustToContents, AdjustToContentsOnFirstShow, AdjustToMinimumContentsLength, AdjustToMinimumContentsLengthWithIcon }

I would suggest

  1. ensuring the SizeAdjustPolicy is actually being used

  2. setting 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.

According to the docs the default SizeAdjustPolicy is AdjustToContentsOnFirstShow so perhaps you are showing it and then populating it?

Either populate it first before showing it or try setting the policy to QComboBox::AdjustToContents.


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.

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:


width = cb->minimumSizeHint().width()

PyQT :

width = cb.minimumSizeHint().width()

Need Your Help

Error: A project with an out put type of class library

c# .net visual-studio-2008

I am trying to figure out .net and got this code that when I try to run from VS 2008 it gives me this error

How to grep for a file extension

regex bash grep

I am currently trying to a make a script that would grep input to see if something is of a certain file type (zip for instance), although the text before the file type could be anything, so for ins...