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) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        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!";
            }
            else
            {
                qDebug() << "The database is open!";
            }
    
            QSqlQuery query("SELECT ID,Pic FROM Items");
    
            if(query.isActive()==true)
              {
                  qDebug() << "The query is active.";
              }
              else
              {
                 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 ();
    
    }
    
    MainWindow::~MainWindow()
    {
        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
 

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