ymoreau
ymoreau

Reputation: 4036

Why QTableView extended selection ignores my default selected row?

The first row is selected by default, when I shift-select the last row I expect that all rows will be selected but no, it only selects the visible rows of the QTableView.

I have a QTableView displaying data from a database-model. It is configured to allow extended selection (ctrl, shift etc) and to select rows only (not cells). The content is changing based on other parameters, and whenever I update the model I select by default the first row of my QTableView.

ui->tableView->setModel(model);

ui->tableView->setColumnHidden(UidColumn, true);

ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

ui->tableView->verticalHeader()->hide();
ui->tableView->setAlternatingRowColors(true);

// This is done whenever the content changes
QModelIndex index = model->index(0,0);
ui->tableView->setCurrentIndex(index);

I hide the vertical headers because nothing to display there, and I hide the first column because it is not relevant for the user.

The first row is displayed as selected, I even logged the changes of focus and the tableView->selectionModel()->selectedRows() is always good (i.e. returning QModelIndex(0,0)). But when I do the shift-click on the last row, it is like the first row was never selected at all.

If I manually select the first row (or any row), the next shift-click will work perfectly. If I do a ctrl-click, the multiselection works perfectly. It is like my default selection (done by the code) is ignored with shift-click.

Upvotes: 1

Views: 962

Answers (1)

ymoreau
ymoreau

Reputation: 4036

The default QModelIndex(0,0) selects a cell that is part of the hidden column. Even if displayed as a selected row, apparently it messes up the shift-selection.

If I do not hide the first column, it works fine.

If I use QModelIndex index = model->index(0,1); it works fine.

A simpler solution is to do ui->tableView->selectRow(0);

Upvotes: 2

Related Questions