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のMethod findText(const qstring&Text)を見ることもできます。指定されたテキストを含む要素のインデックスを返します(発見されていない場合は-1)。この方法を使用する利点は、アイテムを追加するときに2番目のパラメーターを設定する必要がないことです。
ここにちょっとした例があります:
/* 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()はSetedittext()を呼び出すだけです。それ以外の場合、リストに一致するテキストがある場合、currentIndexは対応するインデックスに設定されます。
したがって、コンボボックスが編集できない限り、関数呼び出しで指定されたテキストはコンボボックスで選択されます。
所属していません StackOverflow