Search code examples
pythonpyqtkeyboardpyqt5qtablewidget

Pyqt5 QTableWidget custom keyboard functions


I am using pyqt5 to make a table that user needs to add some information to:

self.table = QTableWidget(Dialog)
self.table.setGeometry(QtCore.QRect(30, 100, 650, 380))
self.tableItem = QTableWidgetItem()

I then use setItem methods to add information to the table.

The user can navigate to different cells of the table by left, right, bottom, and right keys. When the user presses tab, the function is essentially the same as the right key.

However, I want the tab key to go down instead of right. If anyone could direct me to the correct chapters in the documentation or an example to get me started, would be a great help.

Thanks!


Solution

  • A possible solution is to intercept the event of pressing the Tab key and prevent it from propagating using eventFilter(), and believing a key event sends the Down key:

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class Helper(QtCore.QObject):
        def __init__(self, parent=None):
            super(Helper, self).__init__(parent)
            self.m_widgets = []
    
        def appendWidget(self, widget):
            self.m_widgets.append(widget)
            widget.installEventFilter(self)
    
        def eventFilter(self, obj, event):
            if obj in self.m_widgets and event.type() == QtCore.QEvent.KeyPress:
                if event.key() == QtCore.Qt.Key_Tab:
                    # create new event
                    new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, 
                        QtCore.Qt.Key_Down, 
                        QtCore.Qt.NoModifier)
                    # send new event
                    QtCore.QCoreApplication.postEvent(obj, new_event)
                    # if True, the event is discarded
                    return True
            return super(Helper, self).eventFilter(obj, event)
    
    
    class Widget(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            self.table = QtWidgets.QTableWidget(4, 4)
            lay = QtWidgets.QVBoxLayout(self)
            lay.addWidget(self.table)
    
            helper = Helper(self)
            helper.appendWidget(self.table)
    
    
    if __name__ == '__main__':
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())