PDA

View Full Version : With QTableView, `previous.indexes()` is sometime missing cell coordinates.



pfeldman
15th October 2020, 23:13
The code below, which maintains a set containing the coordinates of currently selected cells, works most of the time. But, after editing a cell by double-clicking, `previous.indexes` is missing the coordinates of the cell that was just edited. As a result, errors in `self.final.selection` build up over time. Is there any way to prevent this from happening?

```
def selectionChanged(self, current, previous):
"""
The names `current` and `previous` are misleading. `previous` provides information about
cells that were deselected since the last invocation. `current` provides information
about cells that were just selected.
"""

self.final.previous= []
self.final.current = []

for index in previous.indexes():
r= index.row()
c= self.model.column_map[index.column()]

self.final.previous .append ((r, c))
self.final.selection.discard((r, c))

for index in current.indexes():
r= index.row()
c= self.model.column_map[index.column()]

self.final.current .append ((r, c))
self.final.selection.add ((r, c))

self.update_sig.emit(self)

# If the application provided a callback function, invoke it:
if self.selection_changed:
self.selection_changed(self.final.previous, self.final.current, self.final.selection)
```

d_stranz
15th October 2020, 23:47
The names `current` and `previous` are misleading. `previous` provides information about
cells that were deselected since the last invocation. `current` provides information
about cells that were just selected.

Actually, if you look at the official Qt docs for QAbstractItemView::selectionChanged() you will see that the two arguments are named "selected" and "deselected", respectively. Whatever python Qt wrapping you are using has named them in a misleading way.

In general, if your model changes as a result of editing or some other action, you cannot be guaranteed that any QModelIndex will be valid after the changes are processed. QModelIndex will only be valid during the scope of whatever method has provided it to you (signal, index(), etc.). See the discussion in the Qt docs, especially concerning QPersistentModelIndex.

pfeldman
16th October 2020, 19:08
I've been attempting to determine what's currently selected by accumulating information from `selected` and `deselected`, but this eventually diverges from the truth. Is there a direct way to get information re. what cells are currently selected?

d_stranz
16th October 2020, 21:23
You should probably be using a QItemSelectionModel on your view.

ChristianEhrlicher
17th October 2020, 18:11
Is there a direct way to get information re. what cells are currently selected?
That's exactly what the parameter selected in selectionChanged() contains and the same as QItemSelectionModel::selectedIndexes()