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?
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); }
You can also have a look at the method findText(const QString & text) from QComboBox; it returns the index of the element which contains the given text, (-1 if not found). The advantage of using this method is that you don't need to set the second parameter when you add an item.
Here is a little example :
/* Create the comboBox */ QComboBox *_comboBox = new QComboBox; /* Create the ComboBox elements list (here we use QString) */ QList<QString> stringsList; stringsList.append("Text1"); stringsList.append("Text3"); stringsList.append("Text4"); stringsList.append("Text2"); stringsList.append("Text5"); /* Populate the comboBox */ _comboBox->addItems(stringsList); /* Create the label */ QLabel *label = new QLabel; /* Search for "Text2" text */ int index = _comboBox->findText("Text2"); if( index == -1 ) label->setText("Text2 not found !"); else label->setText(QString("Text2's index is ") .append(QString::number(_comboBox->findText("Text2")))); /* setup layout */ QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(_comboBox); layout->addWidget(label);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With