Search code examples
c++qt4qcombobox

Set Value to QComboBox from QStringList


In my Qt C++ GUI application I have a QDialog window, there I have a few line-edits and I am setting the display texts by function call and setText(). I have stored the values in a QStringList (the QStringList I am populating via Database Query) and setting text as follows--

void MyDialog::setDataToForm(QStringList sl)
{
        ui->nameLineEdit->setText(sl[0]);
        ui->emailLineEdit->setText(sl[1]);
}

Now, I have a QComboBox as well (GenderComboBox). I have set three items there - Male, Female, Other (through QT Creater Layout editor). In my QStringList sl, this value is getting saved in sl[2].

How can I set the value of sl[2] to QComboBox ???


Solution

  • You need to set the currentIndex of the QComboBox:

    QStringList genderList;
    genderList << "Male" << Female" << "Other";
    ui->genderComboBox->setCurrentIndex(genderList.indexOf(sl[2]));
    

    While this works for your example, I suggest having a look at the samples provided in the Qt documentation (Books example, SQL Widget Mapper Example) which use models to automatically populate widget contents based on SQL tables.