Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the keyPressEvent method work in this program?

Tags:

pyqt

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()
like image 854
Ci3 Avatar asked Aug 28 '12 02:08

Ci3


1 Answers

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.
like image 124
FrankieTheKneeMan Avatar answered Nov 05 '22 10:11

FrankieTheKneeMan