How to insert new row under a selected row in my QStandardItemModel in a TableView ?
-
Hi,
What to change in this code to be able to insert new row under a selected row in my QStandardItemModel in a TableView ?My code insert new row after the last row of the table:
void MainWindow::on_Add_Row_Button_clicked() { mModel->insertRow(mModel->rowCount()); }
i can delete selected row by this code:
void MainWindow::on_Delete_Row_Button_clicked() { QModelIndexList indexes = m_ui->Table_CSV->selectionModel()->selectedRows(); while (!indexes.isEmpty()) { mModel->removeRows(indexes.last().row(), 1); indexes.removeLast(); } }
-
@imene said in How to insert new row under a selected row in my QStandardItemModel in a TableView ?:
My code insert new row after the last row of the table:
mModel->insertRow(mModel->rowCount());
I'm quite sure you previously asked just this a few days and I answered there. The answer really is perfectly evident for this
insertRow()
, and is also clearly in the documentation. -
Hi @JonB,
in fact at the begeninig i didn't understand the role of mModel->rowCount() inside insertRow() here did you have any idea about it ?
Now i get it it returns number of the row just added.
How can i get the index of selected row to put it into: insertRow() ? -
@imene
Yes, I don't see how you can not follow what it does! :) Let's read bool QAbstractItemModel::insertRow(int row, const QModelIndex &parent = QModelIndex())Inserts a single row before the given row in the child items of the parent specified.
(For a table rather than a tree, which is what you have, ignore
parent
, it's optional, don't specify anything for that.) When you insert something, you have to say where to insert it. And the docs tell you that is just what theint row
parameter is: it inserts the row immediately before the row number you specify. Now is that not crystal clear? :)So if, for example, you specified
0
forrow
it would insert your new row immediately before/above row #0, so the newly inserted row would be the (new) very first one in the table. Now, you were specifyingmModel->rowCount()
for that --- which is 1 beyond the last row in the table (rows count from0
torowCount() - 1
). So if it inserts before that it means it must insert at the end of the table, after the last row. So that's why it appears there with that code --- inserting atrowCount()
appends a row to the table. -
@JonB said in How to insert new row under a selected row in my QStandardItemModel in a TableView ?:
insertRow()
Yeah it's so clear now Thanks a lot:
So if i want to add a new row under a selected line, i have to add +1 the index value isn't it ?
I'm gonna work on it and share results with you.