QComboBox – 根据项目的数据设置选定的项目

从基于枚举的唯一值的预定义列表中selectQTcombobox中的项目的最佳方式是什么?

在过去,我已经习惯了.NET的select风格,通过将所选属性设置为您希望select的项目的值来select项目:

cboExample.SelectedValue = 2; 

如果数据是一个C ++枚举,是否有QT基于该项目的数据做到这一点?

用findData查找数据的值,然后使用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); } 

你也可以看看QComboBox的findText(const QString&text)方法; 它返回包含给定文本的元素的索引,(如果找不到则返回-1)。 使用此方法的优点是,您添加项目时不需要设置第二个参数。

这是一个小例子:

 /* 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); 

如果您知道要selectcombobox中的文本,只需使用setCurrentText()方法来select该项目。

 ui->comboBox->setCurrentText("choice 2"); 

从Qt 5.7文档

如果combobox是可编辑的,则setter setCurrentText()仅调用setEditText()。 否则,如果列表中有匹配的文本,则将currentIndex设置为相应的索引。

所以只要combobox不可编辑,函数调用中指定的文本将在combobox中被选中。

参考: http : //doc.qt.io/qt-5/qcombobox.html#currentText-prop