Populating sublassed QAbstractItemModel
When trying to insert items into my QAbstractItemModel:
Code:
ListModel * model = new ListModel();
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 4; ++column) {
model->insertRow(1);
qDebug
() << model
->setData
(model
->index
(row
),
QVariant::QVariant("halooo"),Qt
::EditRole);
qDebug() << model->data(model->index(row),Qt::EditRole);
}
}
Outputs:
Code:
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
listmodel.h
Code:
#ifndef LISTMODEL_H
#define LISTMODEL_H
#include <QAbstractListModel>
#include <QStringList>
{
Q_OBJECT
public:
explicit ListModel
(QObject *parent
= 0);
Qt
::ItemFlags ListModel
::flags(const QModelIndex &index
) const;
private:
signals:
public slots:
};
#endif // LISTMODEL_H
listmodel.cpp
Code:
#include "listmodel.h"
#include <QtDebug>
ListModel
::ListModel(QObject *parent
) :{
}
{
// if an invalid row, return empty QVariant
if (index.row() < 0 || index.row() >= 4)
switch( role )
{
case Qt::DisplayRole:
case Qt::EditRole:
{
s
= QString("row [%1]").
arg( index.
row() );
}
default:
}
}
{
if (index.isValid() && role == Qt::EditRole) {
stringList.replace(index.row(), value.toString());
emit dataChanged(index, index);
return true;
}
return false;
}
Qt
::ItemFlags ListModel
::flags(const QModelIndex &index
) const{
if (!index.isValid())
return Qt::ItemIsEnabled;
}
int ListModel
::rowCount(const QModelIndex &parent
) const {
return stringList.count();
}
It seems like the index passed is never valid, "index.isValid()", so it never sets the data. What's wrong here?
Re: Populating sublassed QAbstractItemModel
You did not implement insertRows().
When your example code calls insertRow(), your string list stays at size 0 and so does rowCount().
If all you are storing is a list of strings and you are adding them from outside instead of having the model interfacing to already existing data, why not just use QStringListModel?
Cheers,
_
Re: Populating sublassed QAbstractItemModel
Yes, QStringListModel is what I should use. Do I have to create a custom class to set my model as not edotable?
Re: Populating sublassed QAbstractItemModel
Re: Populating sublassed QAbstractItemModel
The only way I know is to reimplement flags():
Code:
Qt
::ItemFlags ListModel
::flags(const QModelIndex &index
) const{
if (!index.isValid())
return Qt::ItemIsEnabled;
}