2010-12-02 56 views
36

從基於枚舉的唯一值的預定義列表中選擇QT組合框中項目的最佳方式是什麼?QComboBox - 根據項目數據設置選定的項目

在過去,我已經習慣了.NET的在那裏的項目可以通過選擇屬性設置爲項目的值來選擇選擇的風格,你希望選擇:

cboExample.SelectedValue = 2; 

反正有沒有做到這一點如果數據是C++枚舉,QT基於項目的數據?

回答

76

您查找與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); 
} 
+0

+1,你應該提到如何設置,雖然該數據。 – 2010-12-03 06:40:31

21

你也可以看看該方法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); 
+0

使用findText()永遠不會好。 findData()應該是首選的方法。 – hfrmobile 2017-03-07 13:11:29

+2

你的陳述是矛盾的。我同意findData應該是「首選」的方式,但不是唯一的方法。我正在爲現有系統編寫邏輯,有時會使用空數據值創建「簡單」組合框內容。所以通常findData就足夠了,但是當沒有「數據」查找時,有時候你需要findText。 – TheGerm 2017-06-13 22:14:21

1

如果您知道您要選擇組合框中的文本,只需使用setCurrentText()方法來選擇該項目。

ui->comboBox->setCurrentText("choice 2"); 

從Qt的5.7文檔

的二傳手setCurrentText()簡單地調用setEditText()如果組合 框可編輯。否則,如果列表中有匹配的文本,則 currentIndex被設置爲相應的索引。

所以只要組合框不可編輯,函數調用中指定的文本將在組合框中選定。

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