How to add a row to a subclass of QAbstractTableModel?
-
I have a subclass of QAbstractTableModel which internally manages a vector of tuples.
I need to insert a new row at a certain row number. How can this be done?Can I just insert a tuple into the vector and ask the model to redisplay but not loosing the current row?
How do I find out which is the current row number in the QTableView?Regards,
Juan -
@jdent said in How to add a row to a subclass of QAbstractTableModel?:
I need to insert a new row at a certain row number. How can this be done?
Re-implement
QAbstractTableModel::insertRows
Can I just insert a tuple into the vector and ask the model to redisplay but not loosing the current row?
It might work, but is a bad idea.
How do I find out which is the current row number in the QTableView?
rowCount()
, also re-implement it in your model, so it always returns the correct number of rows.For more detail check out the Editable TreeView Example
(it's TreeView but in general the insert/remove procedure of rows and cols is the same) -
@jdent said in How to add a row to a subclass of QAbstractTableModel?:
How do I find out which is the current row number in the QTableView?
Depending on what you want, any of the following:
- QModelIndex QAbstractItemView::currentIndex() const
- QModelIndexList QTableView::selectedIndexes() const
- QItemSelectionModel *QAbstractItemView::selectionModel() const and call QModelIndex QItemSelectionModel::currentIndex() const
However, note that usually you do not need the currently selected row number. If you are asking about this in order to preserve/restore the current row after making a change: if you insert/delete/update a row I think you will find the table view maintains the currently selected row for you.
If you refill/invalidate the whole table and wish to retain/restore the previous current row you should (probably) not do that by row number as that may have changed due to to the new data. Rather you should look at the data in the current row before the refresh, keep some "primary key" which uniquely identifies the data in that row, refill the data, find the index in the new data of the saved "primary key" and call void QItemSelectionModel::select(const QModelIndex &index, QItemSelectionModel::SelectionFlags command) to reselect wherever that item appears in the model's new data.
-
@Pl45m4 said in How to add a row to a subclass of QAbstractTableModel?:
For more detail check out the Editable TreeView Example
(it's TreeView but in general the insert/remove procedure of rows and cols is the same)https://doc.qt.io/qt-6/qtwidgets-itemviews-editabletreemodel-example.html
@jdent see here