PDA

View Full Version : Remove selected rows from a QTableView



niko
17th December 2006, 18:22
I have a QTableView and a subclassed QStandardItemModel.

I need a Button wich deletes the selected rows. This is my current implementation:

//get selections
QItemSelection selection = tableView->selectionModel()->selection();

//find out selected rows
QList<int> removeRows;
foreach(QModelIndex index, selection.indexes()) {
if(!removeRows.contains(index.row())) {
removeRows.append(index.row());
}
}

//loop through all selected rows
for(int i=0;i<removeRows.count();++i)
{
//decrement all rows after the current - as the row-number will change if we remove the current
for(int j=i;j<removeRows.count();++j) {
if(removeRows.at(j) > removeRows.at(i)) {
removeRows[j]--;
}
}
//remove the selected row
model->removeRows(removeRows.at(i), 1);
}


which works - but can't this be easier?

thanks for any suggestions.

niko

jacek
17th December 2006, 18:53
QItemSelection selection( tableView->selectionModel()->selection() );

QList<int> rows;
foreach( const QModelIndex & index, selection.indexes() ) {
rows.append( index.row() );
}

qSort( rows );

int prev = -1;
for( int i = rows.count() - 1; i >= 0; i -= 1 ) {
int current = rows[i];
if( current != prev ) {
model->removeRows( current, 1 );
prev = current;
}
}

yarovenkoas
2nd March 2016, 06:09
My code im using


QModelIndexList indexes = ui->tableUserVars->selectionModel()->selectedRows();
int countRow = indexes.count();

for( int i = countRow; i > 0; i--)
modelUserVars->removeRow( indexes.at(i-1).row(), QModelIndex());



And if you are working with a large number of rows ( > 100,000 ) and the selection of lines in order not to sample the rapid removal of this way + if the selection is selectively remove the row from selectionModel

My code im using fast delete rows > 1000000


QModelIndexList indexes = ui->tableUserVars->selectionModel()->selectedRows();
int countRow = indexes.count();

bool flagDif = false;
for( int i = countRow; i > 1; i--)
if (indexes.at(i-1).row()-1 != indexes.at(i-2).row())
flagDif = true;

if (!flagDif)
modelUserVars->removeRows(indexes.at(0).row(),countRow,QModelInde x());
else
for( int i = countRow; i > 0; i--)
modelUserVars->removeRow( indexes.at(i-1).row(), QModelIndex());


Ps. Sorry bad englsh.

d_stranz
2nd March 2016, 16:20
And why are you posting this in response to a 10 year old thread???

yarovenkoas
3rd March 2016, 12:49
maybe someone will come in handy =)