Looping through query results and displaying in tableview

  • Hi,
    My intention is to use the following code to read all the data from the database and list them in tableview. ```
    //your code #include "mainwindow.h"
    #include "ui_mainwindow.h"

    MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)

    QSqlDatabase db;
           db = QSqlDatabase::addDatabase ("QSQLITE");
           db.setDatabaseName ("C:/Programming/Qtsamples/Image_from_db_to_Table/db.db");
           if(!db.open ())
               qDebug() << "The database is NOT open!";
               qDebug() << "The database is open!";
           QSqlQuery query("SELECT * FROM Items ");
                 qDebug() << "The query is active.";
                qDebug() << "The query is NOT active.";
           QSqlQuery query2 ("SELECT Count(*) FROM Items");
    		int count;
           query2.first ();
            count = query2.value (0).toInt ();
    		qDebug() << "The number of rows: " << count;
    		//query.first ();
            QStandardItemModel *smodel = new QStandardItemModel;
            int ID;
    		ui->tableView->setModel (smodel);
    while(query.next ())
                    QStandardItem *Item = new QStandardItem();
                    QStandardItem *Item2 = new QStandardItem();
                    Item->setData (ID = query.value (0).toInt (),Qt::DisplayRole);
                    qDebug() << "ID = " <<   ID;
                    smodel->setItem (0,0,Item);
                    QByteArray ByteArray;
                    ByteArray = query.value (1).toByteArray ();
                    QPixmap Pixmap;
                    Pixmap.loadFromData (ByteArray);
                    Pixmap = Pixmap.scaled (100,100,Qt::KeepAspectRatio);
                    Item2->setData (QVariant(Pixmap),Qt::DecorationRole);
                    smodel->setItem (0,1,Item2);
    				ui->tableView->resizeColumnsToContents ();
    				ui->tableView->resizeRowsToContents ();
          			ui->tableView->horizontalHeader ()->setStyleSheet ("QHeaderView{font: 14pt Arial; color: blue; font-weight: bold;}");
          smodel->setHeaderData (0,Qt::Horizontal, QObject::tr ("ID"));
          smodel->setHeaderData (1,Qt::Horizontal, QObject::tr ("Picture"));
    	db.close ();


    delete ui;

    The code only lists the first item in the database. Please help me to find what I did wrong. Thank you.

  • Qt Champions 2017

    @gabor53 said:
    Well the query seems fine.
    But one thing I did wonder;

    smodel->setItem (0, 0, Item);
    smodel->setItem (0, 1, Item2);

    You inset as same row ? (0)
    I imagine something like

    int row=0
    while(query.next ()) {
    smodel->setItem (row, 0, Item);
    smodel->setItem (row++, 1, Item2);

    Also for viewing, there is also

  • Thank you. It worked.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.