QComboBox - 根据项目数据设置选定项目

62

如何以预定义的基于enum独特值的方式从QT组合框中选择项目,这将是最佳方法?

过去我已经习惯了.NET的选择方式,其中可以通过将选定的属性设置为所需选择的项目的值来选择该项目:

cboExample.SelectedValue = 2;

如果数据是C++枚举类型,基于项的数据,有没有用QT实现这个的方法?

3个回答

125
你可以使用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);
}

28
你还可以查看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);

使用findText()从来不是一个好的选择。应该优先考虑使用findData()。 - hfrmobile
5
你的陈述有矛盾之处。我同意findData应该是“首选”的方法,但不是唯一的方法。我正在为一个现有系统编写逻辑,有时会创建带有空数据值的“简单”下拉框内容。因此通常使用findData就足够了,但有时候当没有“数据”可查找时需要使用findText。 - TheGerm

11
如果您知道要选择的组合框中的文本,只需使用setCurrentText()方法选择该项即可。
ui->comboBox->setCurrentText("choice 2");

来自 Qt 5.7 文档

如果组合框是可编辑的,则 setCurrentText() 函数简单地调用 setEditText() 函数。否则,如果列表中有匹配的文本,则将 currentIndex 设置为相应的索引。

因此,只要组合框不可编辑,在函数调用中指定的文本将在组合框中被选择。

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


ui->comboBox->setCurrentText("option") 是有效且简单的方法! - sonichy
也许值得注意的是,这在Qt 4.x中不可用,至少不是在4.8版本中。 - Hawkins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接