Search code examples
qtqlistviewqt5.3

QlistView setCurrentIndex() not working


I am facing a problem with a QListView component.

I created a simple form with a listview and a tableview. Then I put this code, both widgets populate with the data model as I want:

QSqlQueryModel * modela = new QSqlQueryModel();
QSqlQueryModel * modelb = new QSqlQueryModel();

[...]

ui->listView->setModel(modela);
ui->tableView->setModel(modelb);

[...]

void MyWindow::on_listView_clicked(const QModelIndex &index)
{
 ui->tableView->setCurrentIndex(ui->listView->currentIndex());
}

void MyWindow::on_tableView_clicked(const QModelIndex &index)
{
 ui->listView->setCurrentIndex(ui->tableView->currentIndex()); 
 // FAILS, does not react...  
}

The first slot (when I click any item in the listview widget) works as expected, it automatically selects the corresponding item in the tableview widget, but the second case does not work, it just does not select any item in the listview...

What I want is that whatever item the user clicks in the tableview gets selected in the listview.

Is it possible? I tried hard, looking for examples and the official qt documentation, but I don't find the right way to do (also tried to connect with signal/slots, but I don't know how to exactly connect both widgets).

Thanks in advance.


Solution

  • QModelIndex is an integral part of a certain QAbstractItemModel. It means that you can't use an index from model A to select an item in a view of model B.

    QModelIndex is not just a couple of x,y. It also keeps a pointer to a model which created it.

    So if you need to select the same row as selected in the first view, you need to extract a row from the first index, then get a right index in the second model and use it to select an item in the second view:

    void selectTheSameRow(const QModelIndex& indexFromModelA)
    {
      int row = indexFromModelA.row();
      QModelIndex indexFromModelB = modelB->index(row, 0);
      viewB->setCurrentIndex(indexFromModelB);
    }