Get list of selected rows from QTableView
win32:qt4.01
I have a QTableView loaded with an QSqlTableModel. I have the selection method set to extended. I select multiple rows and have everything set to delete them but i just need to know which are selected. currentIndex() only gives the last selected item. Any ideas?
Re: Get list of selected rows from QTableView
Code:
QSelectionModel *selections = tableView->selectionModel();
QModelIndexList selected = selections->selectedIndexex();
Re: Get list of selected rows from QTableView
ok that works sorta.
This is what i have
Code:
QModelIndexList selected = selections->selectedIndexes();
for( i = 0 ; i < selected.size(); i++ )
{
rowid = selected[i].row();
but size() doesn't return the correct number of selected items.
Re: Get list of selected rows from QTableView
whoops!
QModelIndexList is filled with (rows*columns).
How do you just get the rows that have been selected?
Re: Get list of selected rows from QTableView
Now i'm running into the problem that when i remove a row using m_TableModel->removeRow( rowid ) it screws up the rest of the removes that i want to do. I can't use removeRows() because that doesn't work for non-adjacent selections.
I could switch to making an sql query for delete but that would sort of defeat the purpose of having a model
Re: Get list of selected rows from QTableView
Check those indexes. Each index has a row and column number in it. Besides, if you set your model (or view? I don't remember right now), it'll only allow selecting whole rows, so it should be easy to find row numbers (for example ignore every index with column number not equal to 0, this way you'll be processing only 0-th columns, and the number of such items will be the number of rows selected).
Re: Get list of selected rows from QTableView
I had the same problem lately, and found maps very convenient for the job:
Code:
void ALocalvalueTableView::removeSelected()
{
QMap<int, int> rows;
rows.insert(index.row(), 0);
QMapIterator<int, int> r(rows);
r.toBack();
while (r.hasPrevious()) {
r.previous();
model()->removeRow(r.key());
} // while
} // removeSelected
Re: Get list of selected rows from QTableView
So you use map to go to the end of the list and remove them from highest to lowest rowid? Sounds like a plan. Thanks for all the info.
Re: Get list of selected rows from QTableView
The nice thing about the map is that it automaticly eliminates duplicates. The reverse delete order is important ;)