将Value设置为QStringList中的QComboBox

Set Value to QComboBox from QStringList

本文关键字:中的 QComboBox QStringList Value 设置      更新时间:2023-10-16

在我的Qt c++ GUI应用程序中,我有一个QDialog窗口,在那里我有一些行编辑,我通过函数调用和setText()设置显示文本。我已经将值存储在QStringList(我通过数据库查询填充的QStringList)中,并设置文本如下——

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

现在,我也有一个QComboBox (GenderComboBox)。我在那里设置了三个项目-男性,女性,其他(通过QT创建布局编辑器)。在我的QStringList sl中,这个值被保存在sl[2]中。

如何将sl[2]的值设置为QComboBox ??

需要设置QComboBoxcurrentIndex:

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

虽然这适用于您的示例,但我建议查看Qt文档中提供的示例(Books示例,SQL Widget Mapper示例),该示例使用模型根据SQL表自动填充小部件内容。