enum
ベースの一意の値の定義済みリストから QT コンボ ボックス内の項目を選択する最良の方法は何でしょうか。
過去に、selected プロパティを選択したい項目の値に設定することで項目を選択できる .NET の選択スタイルに慣れてきました。
cboExample.SelectedValue = 2;
データがC++列挙型の場合、項目のデータに基づいてQTでこれを行う方法はありますか?
enum
ベースの一意の値の定義済みリストから QT コンボ ボックス内の項目を選択する最良の方法は何でしょうか。
過去に、selected プロパティを選択したい項目の値に設定することで項目を選択できる .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) を見ることもできます。指定されたテキストを含む要素のインデックスを返します (見つからない場合は -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のドキュメントから
セッター setCurrentText() は、コンボ ボックスが編集可能な場合、単純に setEditText() を呼び出します。それ以外の場合、一致するテキストがリストにある場合、currentIndex は対応するインデックスに設定されます。
したがって、コンボ ボックスが編集可能でない限り、関数呼び出しで指定されたテキストがコンボ ボックスで選択されます。