首页 > 解决方案 > 当我在 pyqt5 中按 Enter 时转到下一个 LineEdit

问题描述

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

有人有建议吗?

标签: pythonpyqt5qtwidgets

解决方案


一种可能的解决方案是拦截 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())

推荐阅读