Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 813
cweston Avatar asked Dec 02 '10 21:12

cweston


2 Answers

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); } 
like image 72
Martin Beckett Avatar answered Sep 17 '22 19:09

Martin Beckett


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); 
like image 28
Aloïké Go Avatar answered Sep 17 '22 19:09

Aloïké Go