Important: Please read the Qt Code of Conduct -

Getting database values into QStringList

  • In my qt c++ application I want to Query a database table and to insert the values into a QStringList!

    Following is my code!

    void Dialog::on_pushButton_clicked()
    QStringList Names;

            QSqlQuery qry(QSqlDatabase::database("MyConnection"));
            qry.prepare("Select NAME from User where NAME like '%Ab%' ");



    The Query is executed successfully but I dont know how to get the NAME values into the QStringList! How can I achieve it?

  • @Lasith
    you can iterate over results with QSqlQuery::next() and get values with QSqlQuery::value().

    bool prepRet = query.prepare("Select NAME from User where NAME like '%Ab%' ");
    if (!prepRet) {
         qDebug() << query.lastError().text();
    if (!query.exec()) {
         qDebug() << query.lastError().text();
    QStringList list;
    while ( {
        list << query.value(0).toString();

    EDIT: error reporting

  • Lifetime Qt Champion


    To add to @dream_captain, in case of an error, at least print the error string from the query so you know what went wrong.