How to sort QAbstractListModel
-
what do you mean you "cannot see sort() method"?
Do you mean in the Qt source code?
Its implemented in QAbstractItemModel class. And it's implemented empty there of course.
Since it's an Abstract class it's not clear how the data is stored inside the model and thus it would be impossible to be implemented there.For example you can use QStringListModel which already has it implemented, since it also already has the data storage implemented.
But if you need to subclass QAbstractListModel you also have to implement the sort() method yourself.
-
The abstractItemModel does NOT hold the data. It's just a defined class so that a View is able to call predetermined functions to set/read data etc. You should subclass het AbstractItemModel and write code in your class that holds the data. e.g. a QList.
The sorting of the View is not relevant to the data in the model. Like Andre, use a SortFilterProxy between your model and the View. The SortFilter knows which item in the View is connected with which item in the Model.
When data is inserted (externally and not from the view) you should call the reset function of the View so to reread all data. Better to read the Model/View stuff first. -
That's even better ;-)
-
I tried this.
@
QSortFilterProxyModel *proxy = new QSortFilterProxyModel;
proxy->setSourceModel(model);// inherists QAbstractListmodel
proxy->sort(0);
view->setModel(proxy);//this is QLisView;view->setitemDelegate(delegate);// to paint the view;
@
but no result. the output is the same(unsorted list) -
The proxy class creates a mapping between the (unsorted) source model, and the sorted representation it presents to its clients. Of course, it can only (by default) sort items it understands: strings, dates, numbers... If you have other items, you will need to subclass QSFPM and reimplement its lessThan virtual function to handle those custom items. Or, you create a role for the sort proxy to use as the sort key, with a data type that the default QSFPM does understand, and then set that role as the sortRole.