PDA

View Full Version : How to remove a multiple selection of rows



aguleo
7th December 2013, 10:12
Hi
When using a QTableView and QSqlTableModel, how do i remove all selected rows?
Removing one is easy ...

model->removeRows(view->currentIndex().row(), 1);

What if there are multiple rows selected with SHIFT and CTRL ....

ChrisW67
7th December 2013, 19:52
You use the view's selectionModel() to get the selected rows (which may have nothing to do with the current index), sort them, and remove them from highest to lowest.

aguleo
10th December 2013, 11:56
If i have a 3 columns view and i select n lines like this:

QItemSelection selection( view->selectionModel()->selection() );
QModelIndexList indexes = selection.indexes();
QMessageBox msg;
msg.setInformativeText(QString::number(indexes.cou nt()));
msg.exec();
... i get a count of 3 * n !

How do i send only the row index to a list?

ChrisW67
11th December 2013, 03:53
Assuming the selection behaviour is SelectRows:

QModelIndexList selectedIndexes = view->selectionModel()->selectedRows();

Then you have a list of indexes in the first column for rows in the selection.
You could iterate over the indexes extracting the row() from each adding it to a QList<int>. Sort the list in descending order. Delete the rows.

Or you could just use the sort order provided by QModelIndex itself:


qSort(selectedIndexes.begin(), selectedIndexes.end(), qGreater<QModelIndex>());


If the selection behaviour is not SelectRows then call


QModelIndexList selectedIndexes = view->selectionModel()->selectedIndexes();

and build a list of unique row numbers by iterating over that list.