pyqtqtableviewqitemselectionmodel

QTableView: Prevent a user from navigating away from a spesific row


I am having trouble preventing the user form changing the current selection, if the save action did not complete successfully. I can re-select a row using the QTableView's selection models' currentRowChanged signal but although the selection change, the blue selection indicator does not. See the image below.

Example: In the image below the user attempted to add a new row nr 537. But the save action got an error and I don't want the user to navigate away from row 537 before the record is either deleted or edited and then saved

Question: How do I move the blue line to the current selection? (the current selection is the last row) (The QTableView's Selection Behavior is set to select rows)

enter image description here

Here is the code I got so far:

    def __init__(self, parent):
        ...
        self.__tableViewSelectionModel = self.__ui.tableView.selectionModel()
        self.__tableViewSelectionModel.currentRowChanged.connect(self.rowChanged)

    def rowChanged(self, current=None, previous=None):
        if save() == True:
            self.__ui.tableView.clearSelection()
            self.__ui.tableView.selectRow(previous.row())

Solution

  • Replacing this:

    self.__ui.tableView.clearSelection()
    self.__ui.tableView.selectRow(previous.row())
    

    with this:

    QtCore.QTimer.singleShot(0.00001, lambda: self.__ui.tableView.selectRow(previous.row()))
    

    produced the desired outcome