keyPressEvent方法如何在此程序中运行?

时间:2012-08-28 02:33:37

标签: pyqt

我无法理解keyPressEvent方法在此程序中的工作原理。具体来说,这里的“e”是什么? keyPressEvent是使用预先存在的实例“e”重新定义的方法吗?

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.setGeometry(300,300,250,150)
        self.setWindowTitle('Event handler')
        self.show()

    def keyPressEvent(self, e):

        if e.key() == QtCore.Qt.Key_Escape:
            self.close()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:11)

e是"事件"当用户按下某个键时生成的。这在事件处理程序中非常常见,它是一种很好的方式来传递信息(例如哪个键被按下 - 这是用e.key()获取的东西)给事件处理程序,这样我们就可以了结合相关事件并使用单一功能处理它们。

# A key has been pressed!
def keyPressEvent(self, event):
    # Did the user press the Escape key?
    if event.key() == QtCore.Qt.Key_Escape: # QtCore.Qt.Key_Escape is a value that equates to what the operating system passes to python from the keyboard when the escape key is pressed.
        # Yes: Close the window
        self.close()
    # No:  Do nothing.