Search code examples
pythonpython-3.xpyqtpyqt5qtreewidget

How I catch Python PyQt5 QTreeWidget pressing enter (return) key?


I am trying to run enterFunc() when pressing enter (return) key. But not working. Here is the code and what is the true code?:

class myForm(QMainWindow):

    ...
    def keyPressEvent(self,event):
                    if(event.key()==Qt.Key_Enter):
                        enterFunc()
    ...
    myForm.myTreeWidget.keyPressEvent(self,event)
    ...

Solution

  • First xxxEvent are not signals and should not be invoked, if you want to listen to one of them you should use an event filter as shown below, on the other hand you should not use the Qt::Key_Enter key but the Qt::Key_Return key:

    from PyQt5 import QtCore, QtWidgets, uic
    
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            uic.loadUi("ui_mainwindow.ui",self)
            self.myTreeWidget.installEventFilter(self)
    
        def eventFilter(self, obj, event):
            if obj == self.myTreeWidget:
                if  event.type() == QtCore.QEvent.KeyPress:
                    if event.key() == QtCore.Qt.Key_Return:
                        print("enter pressed")
            return super(MainWindow, self).eventFilter(obj, event)
    
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = MainWindow()
        w.show()
        sys.exit(app.exec_())
    

    Or more easily use QShortcut:

    from PyQt5 import QtCore, QtWidgets, uic
    
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            uic.loadUi("ui_mainwindow.ui",self)
    
            shorcut = QtWidgets.QShortcut(QtCore.Qt.Key_Return, 
                self.myTreeWidget, 
                context=QtCore.Qt.WidgetShortcut,
                activated=self.some_function)
    
        def some_function(self):
            print("some_function")
    
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = MainWindow()
        w.show()
        sys.exit(app.exec_())