Set selected item for QComboBox

Karen Tsirunyan picture Karen Tsirunyan · Oct 17, 2013 · Viewed 28.7k times · Source

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 ?

Answer

vahancho picture vahancho · Oct 17, 2013

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