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

Linoliumz picture Linoliumz · Jun 30, 2010 · Viewed 27.5k times · Source

I have a QComboBox that I fill with QString using:

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?

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);

Answer

rubenvb picture rubenvb · Jun 30, 2010

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.