PDA

View Full Version : Get list of selected rows from QTableView



jnk5y
16th February 2006, 23:20
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?

wysota
16th February 2006, 23:52
QSelectionModel *selections = tableView->selectionModel();
QModelIndexList selected = selections->selectedIndexex();

jnk5y
17th February 2006, 00:27
ok that works sorta.

This is what i have


QItemSelectionModel *selections = ui.tableView->selectionModel();
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.

jnk5y
17th February 2006, 01:40
whoops!

QModelIndexList is filled with (rows*columns).

How do you just get the rows that have been selected?

jnk5y
17th February 2006, 01:57
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

wysota
17th February 2006, 01:59
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).

seneca
17th February 2006, 02:06
I had the same problem lately, and found maps very convenient for the job:


void ALocalvalueTableView::removeSelected()
{
QMap<int, int> rows;
foreach (QModelIndex index, selectedIndexes())
rows.insert(index.row(), 0);
QMapIterator<int, int> r(rows);
r.toBack();
while (r.hasPrevious()) {
r.previous();
model()->removeRow(r.key());
} // while
} // removeSelected

jnk5y
17th February 2006, 02:43
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.

seneca
17th February 2006, 17:59
The nice thing about the map is that it automaticly eliminates duplicates. The reverse delete order is important ;)