keyPressEvent 方法在这个程序中是如何工作的? [英] How does the keyPressEvent method work in this program?

查看:43
本文介绍了keyPressEvent 方法在这个程序中是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having trouble understanding how the keyPressEvent method works in this program. Specifically, what is "e" here? Is keyPressEvent a redefined method using a pre-existing instance "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()

推荐答案

e 是用户按下某个键时生成的事件".这在事件处理程序中很常见,这是将信息(例如按下哪个键 - 使用 e.key() 拉出的内容)传递给事件处理程序的好方法,以便我们可以组合相关事件并使用单一功能.

e is the "event" that is generated when a user presses a key. This is pretty common in event handlers, it's a great way to pass information (such as which key got pressed - which is what's getting pulled with e.key()) to event handlers, so that we can combine related events and handle them with a single function.

# 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.

这篇关于keyPressEvent 方法在这个程序中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆