-1

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.

BdT141
  • 13
  • 3
  • create a [example] – Alexander Nov 01 '22 at 09:02
  • 1
    If you want to use custom keys in an item view, you should consider overriding the view's `keyPressEvent` or use a custom delegate instead. QShortCut is probably not the good choice for this, especially if the view is in editing mode. – musicamante Nov 01 '22 at 16:59

1 Answers1

0

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.

BdT141
  • 13
  • 3
  • `del` does not delete an object, it deletes the *reference*. ***IF*** that reference is also the last one for that object, *then* the object is finally destroyed. Since Qt internally reparents objects and some take ownership of others, deleting a python reference is never a safe way to destroy a Qt object, and it most cases it just won't work, or it will be unreliable. – musicamante Nov 01 '22 at 16:57
  • A good lesson to learn, thank you @musicamante! – BdT141 Nov 03 '22 at 05:40