How to add/insert/remove a row in QTableView?

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. 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

      return true;

  bool insertRows(int position, int rows, const QModelIndex &parent)
      beginInsertRows(QModelIndex(), position, position+rows-1);

      insert new rows to the underlying data

      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.

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!
Posted in

Comments are closed, but trackbacks and pingbacks are open.