The simple model/view example often gives beginners an illusion that after they re-implement the 4 virtual functions: rowCount, columnCount, data, headerData, their model is ready to roll. (The root abstract model class QAbstractItemModel has 5 pure virtual functions to be implemented by your subclass: parent, index, rowCount, columnCount, and data. Other abstract model classes inherited from QAbstractItemModel may have some of these pure virtual functions implemented by themselves, leaving others for you to implement.) They take it for granted that after they add/insert/delete data in the model, the view must update itself accordingly and automatically. It seems reasonable because the view can call the model’s rowCount and columnCount function at proper time to know its new dimensions, and call the data function to get the new data. Unfortunately, the model/view framework has not evolved to be that smart. You have to re-implement the insertRows function if your view allows to insert new rows, and you have to re-implement the removeRows function if your view allows to remove rows.
bool removeRows(int position, int rows, const QModelIndex &parent) { beginRemoveRows(QModelIndex(), position, position+rows-1); remove rows from underlying data endRemoveRows(); return true; } bool insertRows(int position, int rows, const QModelIndex &parent) { beginInsertRows(QModelIndex(), position, position+rows-1); insert new rows to the underlying data endInsertRows(); return true; }
Note that there are two ordinary functions: insertRow and removeRow in QAbstractItemModel. Do not re-implement them as they are not virtual functions to be re-implemented by subclass(your model class). They are used for external call and they will call the insertRows and removeRows, respectively, that are re-implemented by your sub-class. Now, if you want to add a new row to the table view, you can call model->insertRow(model->rowCount()); If you need to delete a row from the table view, you can call model->removeRow(rowposition,QModelIndex());
The re-implementation of insertRows and removeRows does not necessarily need to modify the underlying model data in case the data has been modified outside the model class. However, beginRemoveRows/endRemoveRows, beginInsertRows/endInsertRows must be called and the functions must return true. Otherwise, you’ll find although the model data has been changed, the rows for the table view are not added or erased.
Comments are closed, but trackbacks and pingbacks are open.