pythonpyqt5qtablewidgetqshortcut

PyQt5 Keyboard shortcut for QTableWidget stops working when table is cleared


I have a QTableWidget that I want to attach a shortcut to to advance to the next cell when the Enter/Return key is pressed using the code I found below. I reuse the table a couple of times so I call the clear() method in between populating the table for its various uses. The code below works fine for the first round, but as soon as I clear and repopulate the table it looses the shortcut function even though I call the code every time the table is repurposed. I realise I only have to assign the shortcut once, but I need Enter to go to the next row in the same column and since the column numbers might change I need to change the amount of cells to skip so I run the "focusNextPrevChild" function that many times.

for key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
    QtWidgets.QShortcut(key, self.addTransactionTable,
                        partial(HelperFunctions.runFunctionManyTimes,
                                partial(self.addTransactionTable.focusNextPrevChild, True), 
                                len(columns))))

Is there a way to unassign the shortcut and start over with the new number of columns?

I've tried storing the QShortcut objects in a member variable of the MainWindow class in the hopes of "keeping it alive", but that didn't work. With these stored shortcuts I tried to uninitialize them with del in hopes of unassigning them and starting over, but that didn't work.


Solution

  • Ok, so instead of using del to unassign the shortcut, I used the .deleteLater() method to more "formally" delete the objects. That seems to have worked. I still think it is necessary to store the created shortcut objects in order to unassign them later.