PDA

View Full Version : QAbstractTableModel not showing data



rspock
22nd March 2013, 00:56
I'm using QAbstractTableModel subclassing and I can access to the date but when I try to associate theese data to a QtableView model I don't see anything.

This is mi code:

.cpp


#include "guiProductTable.h"

guiProductTable::guiProductTable(int numRows, int numColumns, QList<QMap<QString, QString> > productList)
: m_numRows(numRows),
m_numColumns(numColumns),
products(productList)
{
}

int guiProductTable::rowCount(const QModelIndex& parent) const
{
return m_numRows;
}

int guiProductTable::columnCount(const QModelIndex& parent) const
{
return m_numColumns;
}

QVariant guiProductTable::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || role != Qt::DisplayRole)
return QVariant();

// Return the data to which index points.

switch (index.column()){
case 0:
return products.at(index.row())["name"];
break;
case 1:
return products.at(index.row())["id"];
break;
case 2:
return products.at(index.row())["price"];
break;
case 3:
return products.at(index.row())["barcode"];
break;
default:
return QVariant();
}
}


.h


#ifndef GUIPRODUCTTABLE_H
#define GUIPRODUCTTABLE_H

#include <QtGui>
#include <QtCore>
#include "guiProductTable.h"

class guiProductTable : public QAbstractTableModel
{
//Q_OBJECT

public:
guiProductTable(int numRows, int numColumns, QList< QMap<QString,QString> > productList);
int rowCount(const QModelIndex& parent = QModelIndex()) const;
int columnCount(const QModelIndex& parent = QModelIndex()) const;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
private:
int m_numRows;
int m_numColumns;
QList< QMap<QString,QString> > products;
};

#endif // GUIPRODUCTTABLE_H




guiProductTable productTable(productList.count(),4,productList);
ui->tableView->setModel(&productTable);

/* QVariant uno = productTable.data(productTable.index(0,0));
QVariant due = productTable.data(productTable.index(0,1));
QVariant tre = productTable.data(productTable.index(0,2));
QVariant quattro = productTable.data(productTable.index(0,3));
std::cout<<uno.toString().toStdString()<<due.toString().toStdString()<<tre.toString().toStdString()<<quattro.toString().toStdString();*/


if i remove the comment at the bottom I can see the right output.

If i remove comment here: //Q_OBJECT i get a compiling error

Added after 1 8 minutes:

I'v founded the solution.

I had to move the model from stack area to the heap.

lanz
22nd March 2013, 07:09
Or you can make it class member.

d_stranz
22nd March 2013, 23:30
I'v founded the solution.

I had to move the model from stack area to the heap.

And do you understand why? (And why lanz's suggest will probably also work?)

My guess is that at the same time you solved your problem in this way, you also created a memory leak. But it is hard to say for sure without seeing how you implemented your solution.