How to select next row in QTableView programmatically

/*
 * selectNextRow() requires a row based selection model.
 * selectionMode = SingleSelection
 * selectionBehavior = SelectRows
 */

void MainWindow::selectNextRow( QTableView *view )
{
    QItemSelectionModel *selectionModel = view->selectionModel();
    int row = -1;
    if ( selectionModel->hasSelection() )
        row = selectionModel->selection().first().indexes().first().row();
    int rowcount = view->model()->rowCount();
    row = (row + 1 ) % rowcount;
    QModelIndex newIndex = view->model()->index(row, 0);
    selectionModel->select( newIndex, QItemSelectionModel::ClearAndSelect );
}

You already have the current row index, so use something like the following to get the modelindex for the next row

QModelIndex next_index = table->model()->index(row + 1, 0);

Then you can set that modelindex as the current one using

table->setCurrentIndex(next_index);

Obviously you'll need to make sure you're not running past the end of the table, and there's probably some extra steps to make sure the entire row is selected, but that should get you closer.

Tags:

C++

Qt