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"));