Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[SOLVED] QCombobox size should fit in the largest string



  • Hi,

    I have a QCombobox which contains strings of different length. And I want the length of the combobox should be resized with the largest string. I do it like this:

    @Action_combo_box::Action_combo_box(QStringList char_list, const Scene *scene, QWidget *parent)
    : QComboBox(parent)
    , m_scene(scene)
    {
    qDebug()<<"Original width"<<width();
    set_width(char_list);
    addItems(char_list);
    }

    void Action_combo_box::set_width(const QStringList &char_list){
    //find the lengthiest string
    QString longest;
    for (int i = 0; i < char_list.length(); i++) {
    QString str = char_list.value(i);
    if (str.length() > longest.length())
    longest = str;
    }

    QFontMetrics font_metrics(fontMetrics());
    int width = font_metrics.width(longest);
    qDebug()<<"Longest str width"<<width;
    setMinimumWidth(width);
    

    }@

    The above code does not work and my largest string is always clipped.

    My output is:
    Original width 100
    Longest str width 49

    which looks strange to me.
    Any help??



  • Did you had a look at:
    "setSizeAdjustPolicy":http://qt-project.org/doc/qt-5/qcombobox.html#sizeAdjustPolicy-prop

    with
    "QComboBox::AdjustToMinimumContentsLength":http://qt-project.org/doc/qt-5/qcombobox.html#SizeAdjustPolicy-enum



  • Yes I did. That did not help.

    I solved the problem with

    setMinimumWidth(minimumSizeHint().width());



  • can you mark this as [SOLVED] in the first post title that anyone will know that it has been fixed.


Log in to reply