I have a simple QComboBox
widget, which has 2 values inside: True
and False
.
And I have a QString variable currValue
, which is one of those values. I want to set my widget's current value with currValue
.
I thought that solution is the following:
first lets initialize currValue;
QString currValue = "False";
QComboBox* combo = new QComboBox();
combo->addItem("True");
combo->addItem("False");
combo->setCurrentIndex(combo->findData(currValue));
But it doesn't work. Am I doing something wrong ? And Why QComboBox has no member setCurrentItem() or smth like that ?
If you know the text in the combo box that you want to select, just use the setCurrentText() method to select that item. The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.
When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index.
You actually need to write it in the following way:
QComboBox* combo = new QComboBox();
combo->addItem("True", "True");
combo->addItem("False", "False");
combo->setCurrentIndex(combo->findData("False"));
The problem in your implementation was that you did not set the items' userData, but only text. In the same time you tried to find item by its userData which was empty.
With the given implementation, I just use the second argument of QComboBox::addItem(const QString &text, const QVariant &userData = QVariant()))
function that sets the item's userData (QVariant
).
UPDATE:
The alternative way to find the combo box item is setting the specific role as the second argument for QComboBox::findData()
function. If you don't want to explicitly set the user data, you can refer to the items texts with Qt::DisplayRole
flag, i.e.:
QComboBox* combo = new QComboBox();
combo->addItem("True");
combo->addItem("False");
combo->setCurrentIndex(combo->findData("False", Qt::DisplayRole)); // <- refers to the item text
UPDATE 2:
Another alternative could be using text based lookup function QComboBox::findText()
:
QComboBox* combo = new QComboBox();
combo->addItem("True");
combo->addItem("False");
combo->setCurrentIndex(combo->findText("False"));
I have got answer to my own question.
combo->setCurrentIndex(combo->findText(currValue));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With