1

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.

4

1 回答 1

3

QModelIndex是一定的组成部分QAbstractItemModel。这意味着您不能使用模型 A 中的索引来选择模型 B 视图中的项目。

QModelIndex不只是几个 x,y。它还保留一个指向创建它的模型的指针。

因此,如果您需要选择与第一个视图中选择的同一行,则需要从第一个索引中提取一行,然后在第二个模型中获取正确的索引并使用它来选择第二个视图中的项目:

void selectTheSameRow(const QModelIndex& indexFromModelA)
{
  int row = indexFromModelA.row();
  QModelIndex indexFromModelB = modelB->index(row, 0);
  viewB->setCurrentIndex(indexFromModelB);
}
于 2014-09-16T12:55:40.033 回答