如何在PyQt5中使用按键事件

时间:2019-09-24 17:41:22

标签: python pyqt pyqt5

当我在“ LE1”中输入数字并按下键盘上的“ Enter”键时,我希望“ Add”功能能够运行。选择行进行编辑时,我还希望行编辑清除其文本。

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QLineEdit, QLabel, QGridLayout, QWidget, QDialog

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)
        self.Glayout = QGridLayout(centralWidget)
        self.LE1 = QLineEdit('Input Number',self)
        self.LE1.keyPressEvent(self.KPE)
        Label1 = QLabel('+ 1 =',self)
        self.LE2 = QLineEdit(self)
        self.Glayout.addWidget(self.LE1)
        self.Glayout.addWidget(Label1)
        self.Glayout.addWidget(self.LE2)



    def Add(self):
        Num = float(self.LE1.text())
        math = Num + 1
        ans = str(math)
        self.LE2.setText(ans)



    def KPE(self):
        if event.key() == Qt.Key_Enter:
            self.Add()



if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

keyPressEvent是一种方法,如果您以这种方式覆盖它,则将丢失默认行为,此外,这是不必要的,因为QLineEdit具有returnPressed信号,用于通知是否按下了 Enter

另一方面,将字符串转换为浮点型可能会引发异常,因此应避免这种情况,另一个更好的选择是使用仅允许使用QSpinBox或QDoubleSpinBox数值的小部件,或者至少限制通过适当的QValidator输入QLineEdit。

最后不要使用math一词作为变量名称,因为那是将来可能会引起问题的库的名称。

考虑到上述情况,解决方案是:

from PyQt5.QtWidgets import (
    QApplication,
    QGridLayout,
    QLineEdit,
    QLabel,
    QMainWindow,
    QWidget,
)


class MyWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.LE1 = QLineEdit("Input Number")
        self.LE1.returnPressed.connect(self.add)
        Label1 = QLabel("+ 1 =")
        self.LE2 = QLineEdit()

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        layout = QGridLayout(centralWidget)
        layout.addWidget(self.LE1)
        layout.addWidget(Label1)
        layout.addWidget(self.LE2)

    def add(self):
        try:
            num = float(self.LE1.text())
            num += 1
            self.LE2.setText(str(num))
        except ValueError:
            pass


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())