Please run the following code (I am using Qt 5.9):
QTableWidget* tableWidget = new QTableWidget(2, 2, nullptr);
tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
connect(tableWidget->selectionModel(), &QItemSelectionModel::selectionChanged,
[&](const QItemSelection& selected, const QItemSelection& deselected)
{ qDebug() << "selected =" << selected << endl << "deselected =" << deselected; });
tableWidget->show();
QTimer::singleShot(10000, [=](){ tableWidget->removeRow(0); });
Within 10 seconds, select the first of two rows. You will see debug ouput. It will show you that row 0 was selected by your click. Then, after 10s, row 0 is removed automatically. Debug output now shows that row 1 is selected and row 0 is deselected.
The latter doesn't make any sense to me. When removing row 0 I would expect the "new" row 0 being selected afterwards. Also the visually selected row still is row 0 and row 1 simply doesn't exist anymore.
This also happens with a custom model and generic view and makes my application crash by pointing to a row that does not exist.
Is this desired behavior? Where is my misunderstanding?