从基于枚举的唯一值的预定义列表中选择QT组合框中项目的最佳方式是什么?QComboBox - 根据项目数据设置选定的项目
在过去,我已经习惯了.NET的在那里的项目可以通过选择属性设置为项目的值来选择选择的风格,你希望选择:
cboExample.SelectedValue = 2;
反正有没有做到这一点如果数据是C++枚举,QT基于项目的数据?
从基于枚举的唯一值的预定义列表中选择QT组合框中项目的最佳方式是什么?QComboBox - 根据项目数据设置选定的项目
在过去,我已经习惯了.NET的在那里的项目可以通过选择属性设置为项目的值来选择选择的风格,你希望选择:
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);
}
你也可以看看该方法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);
如果您知道您要选择组合框中的文本,只需使用setCurrentText()方法来选择该项目。
ui->comboBox->setCurrentText("choice 2");
从Qt的5.7文档
的二传手setCurrentText()简单地调用setEditText()如果组合 框可编辑。否则,如果列表中有匹配的文本,则 currentIndex被设置为相应的索引。
所以只要组合框不可编辑,函数调用中指定的文本将在组合框中选定。
+1,你应该提到如何设置,虽然该数据。 – 2010-12-03 06:40:31