Search code examples
c++qtuser-interfacecomboboxqcombobox

QComboBox - set selected item based on the item's data


What would be the best way of selecting an item in a QT combo box out of a predefined list of enum based unique values.

In the past I have become accustomed to .NET's style of selection where the item can be selected by setting the selected property to the item's value you wish to select:

cboExample.SelectedValue = 2;

Is there anyway to do this with QT based on the item's data, if the data is a C++ enumeration?


Solution

  • You lookup the value of the data with findData() and then use setCurrentIndex()

    QComboBox* combo = new QComboBox;
    combo->addItem("100",100.0);    // 2nd parameter can be any Qt type
    combo->addItem .....
    
    float value=100.0;
    int index = combo->findData(value);
    if ( index != -1 ) { // -1 for not found
       combo->setCurrentIndex(index);
    }