[PyQt] Suppress departure from cell in QTableView

Maurizio Berti maurizio.berti at gmail.com
Sat Feb 16 20:05:23 GMT 2019


Working with focus events in item views might be a real headache, since you
have to deal with the whole widget tree hierarchy a view has, including the
editor.

I'd suggest another approach, which makes more sense to me: the
closeEditor() is what actually closes (and eventually commits) data to the
model, and it's called from key events and accepted mousePressEvent()s,
which actually try to close the editor, change the current index and,
eventually, create a new editor).
This is a very basic implementation.

class KeepFocusTable(QtWidgets.QTableView):
    currentEditor = None

    def closeEditor(self, editor, hint):
        self.currentEditor = editor

    def mousePressEvent(self, event):
        if self.state() == self.EditingState and self.currentEditor is not
None:
            self.currentEditor.setFocus()
            self.currentEditor.selectAll()
        else:
            QtWidgets.QTableView.mousePressEvent(self, event)

If you return closeEditor(), the editor will stay active, and the view
state() will be kept as EditingState.
This allows you to keep the focus on the editor when using the [shift-]tab,
enter and escape keys; I also added a currentEditor property that allows to
keep track of the current editor.
The mousePressEvent() can now check the state, since it's still in
EditingState and a currentEditor exists, it will focus it; the selectAll()
is obviously optional, I just added so that the user can clearly see that
the focus has been kept; you might also want to ensure that the cell is
visible (in case the user has scrolled "out" of it) by using scrollTo().

At this point you can add your implementation to check and validate the
contents (for example by using a QValidator inside the closeEditor
implementation), and eventually call the QTableView.closeEditor original
method whenever you find it appropriate.

I hope this helps,
Maurizio

-- 
È difficile avere una convinzione precisa quando si parla delle ragioni del
cuore. - "Sostiene Pereira", Antonio Tabucchi
http://www.jidesk.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20190216/e98b72cb/attachment.html>


More information about the PyQt mailing list