Search code examples
pythonpyqt5qtwidgets

go to next LineEdit when I press Enter in pyqt5


I want when user press Enter on keyboard cursor automatically go to next lineEdit. Like TabOrder but with Enter.

Anybody has a suggestion?


Solution

  • A possible solution is to intercept the KeyPress event and verify that if the Enter key was pressed then call the focusNextPrevChild() method:

    from PyQt5.QtCore import QEvent, Qt
    from PyQt5.QtWidgets import (
        QApplication,
        QComboBox,
        QLineEdit,
        QPushButton,
        QVBoxLayout,
        QWidget,
    )
    
    
    class Widget(QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
    
            lay = QVBoxLayout(self)
            lay.addWidget(QLineEdit())
            lay.addWidget(QPushButton())
            lay.addWidget(QLineEdit())
            lay.addWidget(QComboBox())
    
        def event(self, event):
            if event.type() == QEvent.KeyPress and event.key() in (
                Qt.Key_Enter,
                Qt.Key_Return,
            ):
                self.focusNextPrevChild(True)
            return super().event(event)
    
    
    if __name__ == "__main__":
        import sys
    
        app = QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec())