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)
小智 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)
如果您知道要选择的组合框中的文本,只需使用 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
| 归档时间: |
|
| 查看次数: |
85428 次 |
| 最近记录: |