如何以预定义的基于enum
独特值的方式从QT组合框中选择项目,这将是最佳方法?
过去我已经习惯了.NET的选择方式,其中可以通过将选定的属性设置为所需选择的项目的值来选择该项目:
cboExample.SelectedValue = 2;
如果数据是C++枚举类型,基于项的数据,有没有用QT实现这个的方法?
如何以预定义的基于enum
独特值的方式从QT组合框中选择项目,这将是最佳方法?
过去我已经习惯了.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);
}
/* 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);
ui->comboBox->setCurrentText("choice 2");
来自 Qt 5.7 文档
如果组合框是可编辑的,则 setCurrentText() 函数简单地调用 setEditText() 函数。否则,如果列表中有匹配的文本,则将 currentIndex 设置为相应的索引。
因此,只要组合框不可编辑,在函数调用中指定的文本将在组合框中被选择。