Important: Please read the Qt Code of Conduct -

Displaying an integer in tableView

  • Hi,
    I need to display an ID number (as an integer) in tableview. qDebug() displays the correct ID, but it doesn't show up in tableview.

    #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(! ())
                qDebug() << "The database is NOT open!";
                qDebug() << "The database is open!";
            QSqlQuery query("SELECT ID,Pic FROM Items");
                  qDebug() << "The query is active.";
                 qDebug() << "The query is NOT active.";
            query.first ();
           	int ID;
            QStandardItemModel *smodel = new QStandardItemModel;
            QStandardItem *Item = new QStandardItem();
            QStandardItem *Item2 = new QStandardItem();
            Item->setData (ID = query.value (0).toInt ());
            qDebug() << "ID = " << Item->data ().toInt ();
            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->verticalHeader ()->setDefaultSectionSize (100);
            ui->tableView->horizontalHeader ()->setDefaultSectionSize (100);
            ui->tableView->setModel (smodel);
    db.close ();
        delete ui;

    What should I do differently to see the ID (it is suppose to be 1).
    Thank you.

  • This post is deleted!

  • Moderators

    setData() takes a role parameter. You're not giving it so it uses the default Qt::UserRole + 1. This is not used by the table view. Same goes for data() when you retrieve it.

    You need to set the display role instead: Item->setData(ID = query.value (0).toInt (), Qt::DisplayRole);.

  • Thank you. It worked.

Log in to reply