Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Display Values from database to Qcombobox



  • Hi ! I'm a newbie with QT and c++, I have been trying to display values from Qcombobox from the Database, but no avail. I was wondering if someone can take a look and help me.
    Here's a section of my code

    QSqlQuery query;
    query.prepare("SELECT rep FROM Auth");
    query.exec();
    query.first();
    QString a= query.value(0).toString();
    ui->nnid->addItem(a);

    Thank you


  • Lifetime Qt Champion

    Hi and welcome to the forums.

    If you dont get anything in combobox
    then i guess the SqlQuery dont get any results ?

    update:
    you could try

    if ( ! query.first() )
    qDebug() << "no record";

    QString a= query.value(0).toString();
    ui->nnid->addItem(a);

    to see if it can position on first record.



  • Thank you for taking the time to answer me, however that did not work as well. I honestly don't know what I'm doing wrong, because apart from this, I already have a Crud working.


  • Lifetime Qt Champion

    @xayn13

    Did it show "no record" ?

    or what happens ?

    While you are not checking return values, it does look ok.



  • Sorry I definitely forgot to mention that part.
    no actually nothing showed up !!!



  • actually nevermind, it worked ! thank you !!


  • Lifetime Qt Champion

    @xayn13
    Super :)

    For debugging help , its a good idea to do

    QSqlQuery query;
    query.exec(QString("xxx");
    if (query.next())
    {
    // use it
    } else {
        qDebug() << "SqLite error:" << query.lastError().text() << ", SqLite error code:" << query.lastError().number();
    }
    

    as it does report good stuff in case of something up with the query.



  • that's more or less what I did !
    Thank you though !!



  • @xayn13 Another possible solution is to use QSqlQueryModel:

    QSqlQueryModel *model = new QSqlQueryModel;
    model->setQuery("SELECT rep FROM Auth");
    ui->nnid->setModel(model);
    

Log in to reply