QComboBox - 根据项目的数据设置所选项目

cwe*_*ton 49 c++ user-interface qt combobox qcombobox

从预定义的enum基于唯一值的列表中选择QT组合框中的项目的最佳方法是什么.

在过去,我已经习惯了.NET的选择方式,可以通过将所选属性设置为您想要选择的项目值来选择项目:

cboExample.SelectedValue = 2;
Run Code Online (Sandbox Code Playgroud)

如果数据是C++枚举,是否有基于项目数据的QT执行此操作?

Mar*_*ett 98

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);
}
Run Code Online (Sandbox Code Playgroud)

  • +1,你应该提一下如何设置数据. (2认同)

小智 22

您还可以查看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);
Run Code Online (Sandbox Code Playgroud)

  • 你的陈述是矛盾的.我同意findData应该是"首选"方式,但不是唯一的方法.我正在为现有系统编写逻辑,有时会创建具有空数据值的"简单"组合框内容.所以通常findData就足够了,但有时你需要findText来找不到"数据". (3认同)

Dow*_*Dev 6

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

ui->comboBox->setCurrentText("choice 2");
Run Code Online (Sandbox Code Playgroud)

来自 Qt 5.7 文档

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

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

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