Fix selected items after sorting in QTableWidget

OldPersistentIndexes store selected items during sort operation. They
were wrongly taken from static list of indexes. This change takes them
from parent (QTableWidget) who maintains the list of selected segments.

Task-number: QTBUG-48408
Change-Id: Ie1bc4071a275dd76d113d883ab30ccd4cb1fa625
Reviewed-by: Olivier Goffart (Woboq GmbH) <ogoffart@woboq.com>
This commit is contained in:
Libor Tomsik 2015-09-25 10:04:21 +02:00
parent c7e5e1d9e0
commit 3c449f7da5
2 changed files with 26 additions and 5 deletions

View File

@ -555,9 +555,7 @@ void QTableModel::ensureSorted(int column, Qt::SortOrder order,
LessThan compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan);
std::stable_sort(sorting.begin(), sorting.end(), compare);
QModelIndexList oldPersistentIndexes = persistentIndexList();
QModelIndexList newPersistentIndexes = oldPersistentIndexes;
QModelIndexList oldPersistentIndexes, newPersistentIndexes;
QVector<QTableWidgetItem*> newTable = tableItems;
QVector<QTableWidgetItem*> newVertical = verticalHeaderItems;
QVector<QTableWidgetItem*> colItems = columnItems(column);
@ -573,7 +571,12 @@ void QTableModel::ensureSorted(int column, Qt::SortOrder order,
newRow = oldRow;
vit = colItems.insert(vit, item);
if (newRow != oldRow) {
changed = true;
if (!changed) {
emit layoutAboutToBeChanged();
oldPersistentIndexes = persistentIndexList();
newPersistentIndexes = oldPersistentIndexes;
changed = true;
}
// move the items @ oldRow to newRow
int cc = columnCount();
QVector<QTableWidgetItem*> rowItems(cc);
@ -600,7 +603,6 @@ void QTableModel::ensureSorted(int column, Qt::SortOrder order,
}
if (changed) {
emit layoutAboutToBeChanged();
tableItems = newTable;
verticalHeaderItems = newVertical;
changePersistentIndexList(oldPersistentIndexes,

View File

@ -94,6 +94,7 @@ private slots:
void task262056_sortDuplicate();
void itemWithHeaderItems();
void mimeData();
void selectedRowAfterSorting();
private:
QTableWidget *testWidget;
@ -1565,5 +1566,23 @@ void tst_QTableWidget::mimeData()
delete data2;
}
void tst_QTableWidget::selectedRowAfterSorting()
{
TestTableWidget table(3,3);
table.setSelectionBehavior(QAbstractItemView::SelectRows);
for (int r = 0; r < 3; r++)
for (int c = 0; c < 3; c++)
table.setItem(r,c,new QTableWidgetItem(QStringLiteral("0")));
QHeaderView *localHorizontalHeader = table.horizontalHeader();
localHorizontalHeader->setSortIndicator(1,Qt::DescendingOrder);
table.setProperty("sortingEnabled",true);
table.selectRow(1);
table.item(1,1)->setText("9");
QCOMPARE(table.selectedItems().count(),3);
foreach (QTableWidgetItem *item, table.selectedItems()) {
QCOMPARE(item->row(),0);
}
}
QTEST_MAIN(tst_QTableWidget)
#include "tst_qtablewidget.moc"