josef.van.niekerk
josef.van.niekerk

Reputation: 12121

Trying to select a full row in a Qt QTreeView

I'm trying to select a full row in a QTreeView component using the following code:

const QModelIndex topLeft = model->index(0, 0);
const QModelIndex bottomRight = model->index(model->rowCount(), model->columnCount());
ui->hidDescriptorView->selectionModel()->selection().select(topLeft, bottomRight);

I'm a bit clueless, and been looking around using const_cast etc. to try and get the selection working, but the compiler is giving me the following error:

/.../mainwindow.cpp:93: error: member function 'select' not viable: 'this' argument has type 'const QItemSelection', but function is not marked const
            ui->hidDescriptorView->selectionModel()->selection().select(topLeft, bottomRight);
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I'm coming from a previous bit where I managed to make a selection, but only a single cell would get selected, so I'm trying the above to ensure that the entire row is properly selected, as if the user would have clicked it.

Any help would be much appreciated!

Upvotes: 1

Views: 4205

Answers (2)

Liam lifestyle
Liam lifestyle

Reputation: 11

view.setCurrentIndex(model.index(0, 0, view.rootIndex()));

Upvotes: 0

Frank Osterfeld
Frank Osterfeld

Reputation: 25155

The signature of selection() is

const QItemSelection selection () const

i.e., you cannot modify the QItemSelection in place because it's a const copy. Being a copy, the modification wouldn't have an effect anyway.

Instead, create a copy (alternatively just create a new QItemSelection) and pass it via select():

QItemSelection selection = view->selectionModel()->selection();
selection.select(topLeft, bottomRight);
view->selectionModel()->select(selection, QItemSelectionModel::ClearAndSelect);

As you mentioned that want to select rows, there might be easier ways though:

view->selectionModel()->select(topLeft, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows);

To make selections by the user expand to whole rows:

view->setSelectionBehavior(QAbstractItemView::SelectRows);

Upvotes: 3

Related Questions