2010-12-02 144 views
36

从基于枚举的唯一值的预定义列表中选择QT组合框中项目的最佳方式是什么?QComboBox - 根据项目数据设置选定的项目

在过去,我已经习惯了.NET的在那里的项目可以通过选择属性设置为项目的值来选择选择的风格,你希望选择:

cboExample.SelectedValue = 2; 

反正有没有做到这一点如果数据是C++枚举,QT基于项目的数据?

回答

76

您查找与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); 
} 
+0

+1,你应该提到如何设置,虽然该数据。 – 2010-12-03 06:40:31

21

你也可以看看该方法FINDTEXT从QComboBox(常量QString的&文本);它返回包含给定文本的元素的索引,(如果未找到则返回-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); 
+0

使用findText()永远不会好。 findData()应该是首选的方法。 – hfrmobile 2017-03-07 13:11:29

+2

你的陈述是矛盾的。我同意findData应该是“首选”的方式,但不是唯一的方法。我正在为现有系统编写逻辑,有时会使用空数据值创建“简单”组合框内容。所以通常findData就足够了,但是当没有“数据”查找时,有时候你需要findText。 – TheGerm 2017-06-13 22:14:21

1

如果您知道您要选择组合框中的文本,只需使用setCurrentText()方法来选择该项目。

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

从Qt的5.7文档

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

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

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