当我在 pyqt5 中按 Enter 时转到下一个 LineEdit

go to next LineEdit when I press Enter in pyqt5

我希望当用户在键盘光标上按下 Enter 时自动转到下一行编辑。 与 TabOrder 类似,但带有 Enter。

有人有建议吗?

一个可能的解决方案是拦截 KeyPress 事件并验证是否按下 Enter 键然后调用 focusNextPrevChild() 方法:

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())