Search code examples
pythonpyqtpyqt5qtablewidget

Have Enter key behave like Tab in QTableWidget


I'm using a QTableWidget in PyQt5 and Qt Designer to create a data entry table. What I'd like is a simple way to make the "Enter" keyPressEvent to move across the table like the Tab button was pressed. The following code captures the Enter key press event. How do I make it move the cursor?

def keyPressEvent(self, ev):        
    if ev.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
        print("Enter key pressed")

Solution

  • Instead of using keyPressEvent that is low level you should use QShortcut + focusNextPrevChild() as shown below:

    import sys
    from PyQt5 import QtCore, QtWidgets
    from functools import partial
    
    
    class Widget(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
    
            self.tableWidget = QtWidgets.QTableWidget()
            self.tableWidget.setRowCount(4)
            self.tableWidget.setColumnCount(2)
            for i in range(self.tableWidget.rowCount()):
                for j in range(self.tableWidget.columnCount()):
                    it = QtWidgets.QTableWidgetItem("Cell {}{}".format(i, j))
                    self.tableWidget.setItem(i, j, it)
    
            self.layout = QtWidgets.QVBoxLayout(self)
            self.layout.addWidget(self.tableWidget)
    
            for key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
                QtWidgets.QShortcut(key, self.tableWidget, partial(self.tableWidget.focusNextPrevChild, True))
    
    
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
        ex = Widget()
        ex.show()
        sys.exit(app.exec_())