PDA

View Full Version : QAbstractItemModel question



awhite1159
21st June 2008, 23:33
I am using the QAbstractItemModel and below is the implementation of the data function. I would like to keep my current data structure separate and intact so that is why I chose the abstract rather than the standard. The problem I am having is that I am not sure if I am re-inventing the wheel. Does this code seem unusual and unnecessary? Would I have an easier time using the QStandardItemModel along with a subclassed QStandardItem?

(BUS is a namespace where I defined the icon type ids. I also created a member in my BUSDataMover object that stores the icon type which can be obtained with getIconType())


QVariant TreeModel::data(const QModelIndex &index, int role) const {
if(!index.isValid())
return QVariant();
BUSDataMover* item;
switch(role) {
case Qt::DisplayRole:
item = static_cast<BUSDataMover*>(index.internalPointer());
return item->data(index.column());
break;
case Qt::DecorationRole:
item = static_cast<BUSDataMover*>(index.internalPointer());
if(index.column() != 0)
return QVariant();
switch(item->getIconType()) {
case BUS::NetworkIcon:
return QIcon(":/images/network.png");
break;
case BUS::ClientIcon:
return QIcon(":images/client.png");
break;
case BUS::ServerIcon:
return QIcon(":images/server.png");
break;
case BUS::NICIcon:
return QIcon(":images/nic.png");
default:
return QIcon(":/images/unknown.png");
}
break;
default:
return QVariant();
}
}

wysota
22nd June 2008, 01:04
It's fine, although using QStandardItemModel with a subclassed QStandardItem would be fine as well. In both cases you have to reimplement the data() method and a few others as well - fewer with the QStandardItem method, but if you already implemented the model then this doesn't really matter...

awhite1159
22nd June 2008, 03:18
Thanks Wysota.

One more question. You mention that I could use QStandardItemModel and then subclass QStandardItem. If I were to do this, would I be able to provide a pointer to my custom data structure and then use QStandardItem::UserType for each of the columns in my custom data structure to set/get data?

wysota
22nd June 2008, 10:11
Not exactly. UserType is a constant which marks the beginning of the id space for standard item subclasses. You should reimplement QStandardItem::type() and return a value greater than UserType that will uniquely identify your class, so that you can later identify the type of item (for instance when comparing items using operator<). This has nothing to do with structures or data. To return contents of your structure as different columns of the item you need to reimplement QStandardItem::data() and query your structure for particular piece of data for a particular column of the model. The same goes for QStandardItem::setData() if you want your item to be editable.