Q:

Fit the width of the view to longest item of the QComboBox

I've got a QComboBox which contains long strings. Long means that the strings are wider than the width of QComboBox on my GUI. In this case Qt will display the items in this way:

Previously I was working with MatLab which has a less user friendly GUI but for a drop-down list I think that the MatLab solution is better:

Is there any easy way to achieve a similar result in Qt or do I have to setup a custom model and view for this purpose ?

A:

I've done that few years back. Should be working fine.
//determinge the maximum width required to display all names in full
int max_width = 0;
QFontMetrics fm(ui.comboBoxNames->font());
for(int x = 0; x < NamesList.size(); ++x)
{
    int width = fm.width(NamesList[x]);
    if(width > max_width)
        max_width = width;
}
if(ui.comboBoxNames->view()->minimumWidth() < max_width)
{
    // add scrollbar width and margin
    max_width += ui.comboBoxNames->style()->pixelMetric(QStyle::PM_ScrollBarExtent);
    max_width += ui.comboBoxNames->view()->autoScrollMargin();
    // set the minimum width of the combobox drop down list
    ui.comboBoxNames->view()->setMinimumWidth(max_width);
}

