views:

132

answers:

2

Hi,

I have a QComboBox that I fill with QStrings using:

comboBox->addItem(someString);

When I start my GUI application the width of the comboBox 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?

Thanks!

Edit:

After some further testing I found the following soluiton:

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

Thanks

+1  A: 

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.

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.

Troubadour
Thanks, yes the QComboBox is in a QHBoxLayout. I tried modifying the SizeAdjustPolicy but it had no effect, I also tried populating the QComboBox before calling ui->setupUi(this); in the constructor but the program crashed. The QComboBox was created using Qt Creator, I do not know if it is possible to populate it before it is beeing shown.
walki
What do you have set as the `SizePolicy` on the combobox?
Kaleb Pederson
It makes sense that trying to populate the combo before calling ui->setupUi(this) would cause a segfault, because the QComboBox object hasn't been instantiated yet.Set the AdjustPolicy to QComboBox::AdjustToContents.
Casey
A: 

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.

rubenvb