I'm implementing a QAbstractListModel
-derived class (though this question can apply to QAbstractItemModel
as well) that will be a QListView
's model. The list view is intended to be a log with a maximum number of items that it can display. So it has the following properties:
Basically, my model will have something akin to an appendItem(const MyDataType &val)
function, and depending on the number of items in the list, appending an item might remove an item from the top of the list.
In this case, is it necessary to reimplement insertRows()
and removeRows()
from QAbstractListModel
? These functions seem ill-suited for what I'm doing anyway, because insertRows()
does not specify what data is being added, and yet I need to make a change to my model's underlying data structure to add an item. That only makes sense to do if I have actual data to add.
Can I just write a function like appendItem(const MyDataType &val)
that internally calls beginInsertRows
, endInsertRows
, and if necessary, beginRemoveRows
and endRemoveRows
, and not bother with insertRows
and removeRows
? Or is that using QAbstractItemModel
incorrectly and will cause errors?
The appendItem(...)
approach is valid.
It is exactly akin to void QStandardItemModel::appendRow(const QList<QStandardItem *> &items)
which is nothing more than a method created by the Qt developers themselves solely to make life easier. If it is something they do, why not you?
Note that as soon as you make your model writable from a view, you need to override all these pesky methods from QAbstractItemView
but even in that case, you are free to keep appendItem(...)
as a convenience method.