Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set selected item for QComboBox

Tags:

qt

qcombobox

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 ?

like image 496
Karen Tsirunyan Avatar asked Oct 17 '13 14:10

Karen Tsirunyan


People also ask

How do I set up Qcombobox?

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.

How do I select items in ComboBox?

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.


2 Answers

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"));
like image 127
vahancho Avatar answered Nov 16 '22 00:11

vahancho


I have got answer to my own question.

combo->setCurrentIndex(combo->findText(currValue));
like image 35
Karen Tsirunyan Avatar answered Nov 15 '22 23:11

Karen Tsirunyan