PDA

View Full Version : Subclassing QStandardItemModel to QTrevview



Nightfox
26th July 2009, 17:19
I've created an application that subclasses the QAbstractItemModel to load item from at database and display them in a QTreeview. I store data in a QMap and I've implemented new functions for;

QModelIndex index(int row, int column,const QModelIndex &parent) const;
QModelIndex parent(const QModelIndex &child) const;

int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;

Now I want to change the model from QAbstractItemModel to QStandardItemModel to utilize the sort and findItems functions. I'm changing my implementation class from QAbstractItemModel to QStandardItemModel but now the Qtreeview is empty when I run the code. What going on here?
Does anyone have an example of a QStandardItemModel bieng subclasses (editable) to be used in a QTreeview?

Thanks

wysota
26th July 2009, 18:10
QStandardItemModel has those method you mentioned already implemented. sort() and findItems() from QStandardItemModel will not work with your reimplementations. It will be much easier if you just reimplement appropriate methods for your (abstract item model based) model. In general you can't sort a map, so you either need to implement artificial mapping or switch from using QMap to QList. If you do the latter, sorting items is equivalent to sorting the data container. There is also one alternative to doing all that - wrap your model in a QSortFilterProxyModel and set that as the model for your view.

Nightfox
26th July 2009, 19:26
Thanks for the advise wysota!
I think I will change from QMap to QList.
Actually I was considering the QStandardItemModel for more than one reason. I can't seem to iterate through the tree to retrieve all the QModelIndexes from my model. I want the user to be able to rearrange the items in the tree - for example to move down items and to change the parent of items. My problem is that I must reset the model to refresh the changes - and the reset makes the tree collapse all notes. My workaround was to iterate through the tree items to see which notes are expanded and remember that after the reset. But with the QAbstractItemModel I've found no way of iterating all the QModelindex in the model which is why I was looking to the QStandardItemModel instead.

That was a long story but do you follow?

wysota
26th July 2009, 22:34
Yes, I can follow you quite fine. You'd need to implement a few more methods to make drag and drop available. It's probably more work than switching to QStandardItemModel.