QCOMBOBOX-根据项目的数据设置选定的项目
-
30-09-2019 - |
题
从预定义的列表中选择QT组合框中的项目的最佳方法是什么 enum
基于独特的值。
过去,我已经习惯了.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);
}
其他提示
您还可以查看Qcombobox的方法FindText(const qString&text);它返回包含给定文本的元素的索引( - 如果找不到)。使用此方法的优点是,添加项目时无需设置第二个参数。
这是一个小例子:
/* 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文档中
Setter SetCurrentText()如果组合框可编辑,请简单地调用设置EditText()。否则,如果列表中有匹配的文本,则将CurrentIndex设置为相应的索引。
因此,只要组合框不能编辑,在组合框中将选择函数调用中指定的文本。
不隶属于 StackOverflow