PDA

View Full Version : setData in a model derived from QAbstractTableModel



enno
31st October 2010, 22:03
I expect setData() below to store the string somewhere in the model but the call fails. Do I do something wrong or do I misunderstand what setData() is doing. Same for setHeaderdata()

The simplest code that fails to build the model as I expect is a header file .hpp



#include <QAbstractTableModel>

class Model : public QAbstractTableModel
{
Q_OBJECT
public:
Model(QObject *parent = 0) : QAbstractTableModel(parent) {};

void setSize(int r, int c) {
rows = r;
cols = c;
}

int rowCount(const QModelIndex &parent = QModelIndex()) const { return rows; };
int columnCount(const QModelIndex &parent = QModelIndex()) const { return cols; };;

QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
{ return QVariant(); };
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const
{ return QVariant(); };

private:
int rows, cols;
};



and a source file .cpp


#include <QtGui>
#include <trial.hpp>

int main(int argc, char* argv[]) {
Model* model = new Model();
model->setSize(8,6);

QVariant *v = new QVariant(QString("Some text"));
if( ! model->setHeaderData(0, Qt::Horizontal, *v) )
qDebug() << "Set hdr failed";

v = new QVariant(QString("Some more text"));
QModelIndex mi = model->index(2,4);
if( ! model->setData(mi, *v) )
qDebug() << "Set data failed";
}

Any help most welcome,
Enno

ChrisW67
31st October 2010, 23:14
QAbstractTableModel inherits setData() from QAbstractItemModel. From the docs for QAbstractItemModel::setData():


Sets the role data for the item at index to value.
Returns true if successful; otherwise returns false.
The dataChanged() signal should be emitted if the data was successfully set.
The base class implementation returns false. This function and data() must be reimplemented for editable models.

enno
1st November 2010, 15:11
The above very indirectly solved my problem I mistakenly thought setData() would store data inside the model.

I now realize that I myself have to define the data structure as member of the model to keep data for cells. Programmatically I fill that data structure.
The view uses data() to get at this data. In the case of a TableModel rowCount() and columnCount() simply return the number of rows and columns of that structure.

Only for an editable model is a setData() function required to update the data for a cell as only I know what structure the data is kept in

The obvious is sometimes difficult to see.