QComboBox *comboBox = new QComboBox(); comboBox->addItem("Option 1"); comboBox->addItem("Option 2"); comboBox->addItem("Option 3"); int index = comboBox->findText("Option 2"); // index variable will hold the value 1, which is the index of "Option 2" in the list
QStringList fruits = {"Apple", "Banana", "Orange", "Pear"}; QComboBox *comboBox = new QComboBox(); comboBox->addItems(fruits); QString selectedFruit = "Banana"; int index = comboBox->findText(selectedFruit); if(index != -1) { comboBox->setCurrentIndex(index); }In this example, we have a QStringList holding four fruits. We create a QComboBox and fill it with the fruits. Then, we set the selectedFruit variable to "Banana" and use the findText method to get its index in the list. Finally, we use the setCurrentIndex method to select "Banana" in the ComboBox. Package/Library: QtWidgets (Qt Framework)