PDA

View Full Version : A simplest ListModel... no example :(



tomek
7th January 2006, 00:35
Hi!
I'm trying to make a simplest ListModel accessing QList<Class>.
Could someone take a look and tell me how it should be written?
feed.h:


class Feed
{
public:
Feed();
Feed(const Feed &other);
Feed &operator=(const Feed &other);

QString stringUrl;
QDate lastFetched;
QString htmlContent;
};


feedModel.h:


class Feed;
#include <QAbstractListModel>
class FeedModel : public QAbstractListModel
{
public:
int rowCount ( const QModelIndex & parent = QModelIndex() ) const;
QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const;
private:
QList<Feed> list;

};


feedModel.cpp:


#include "feedModel.h"
#include "feed.h"

#include <QAbstractListModel>

int FeedModel::rowCount ( const QModelIndex & parent ) const
{
if (!parent.isValid())
return (-1);
else
return list.count();
}

QVariant FeedModel::data ( const QModelIndex & index, int role ) const
{
if (!index.isValid())
return QVariant();

if (role != Qt::DisplayRole)
return QVariant();
// This is the hardest place for me!
// Feed *item = static_cast<Feed*>(index.internalPointer());
Feed item = static_cast<Feed>(list.at(index.row()));

switch (index.column()) {
case 0:
return item.stringUrl;
default:
return QVariant();
}
}

Regards!

wysota
7th January 2006, 00:43
You provided invalid addresses for those files. Please attach them properly using the attachment feature. Or post your code here using the [code] tag.

jacek
7th January 2006, 00:52
Could someone take a look and tell me how it should be written?

You can find a short tutorial here (http://doc.trolltech.com/4.1/model-view-creating-models.html).

jacek
7th January 2006, 01:00
// This is the hardest place for me!
// Feed *item = static_cast<Feed*>(index.internalPointer());
Feed item = static_cast<Feed>(list.at(index.row()));
list is a QList<Feed>, so list.at( x ) will return a reference to a Feed instance --- you don't need any casts.

int row = index.row();
if( 0 <= row && row < list.size() ) {
return QVariant();
}
const Feed& item = list.at( row );

wysota
7th January 2006, 01:20
int FeedModel::rowCount ( const QModelIndex & parent ) const
{
if (!parent.isValid())
return (-1);
else
return list.count();
}

Why so? parent is not valid for first level or hierarchy, thus you should return list.count() here...


int FeedModel::rowCount ( const QModelIndex & parent ) const
{
return list.count(); // the model is not hierarchical, so parent is always invalid
}

data() looks fine.

Please note that your model is read only!

tomek
7th January 2006, 01:32
Thank you. Now it's all right!
I think I should improve my C++...
Have a good weekend.