2012-08-28 10 views
7

Ho difficoltà a capire come funziona il metodo keyPressEvent in questo programma. In particolare, cos'è "e" qui? KeyPressEvent è un metodo ridefinito che utilizza un'istanza "e" preesistente?Come funziona il metodo keyPressEvent in questo programma?

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() 

risposta

9

e è l '"evento" che viene generato quando un utente preme un tasto. Questo è abbastanza comune nei gestori di eventi, è un ottimo modo per passare informazioni (come ad esempio il tasto premuto - che è ciò che viene trascinato con e.key()) ai gestori di eventi, in modo che possiamo combinare eventi correlati e gestirli con una singola funzione.

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

Non ho molta familiarità con i gestori di eventi, ma suppongo che la chiave() sia definita in Qt? Quindi, quando viene premuto un tasto, passa a questa funzione. Grazie per l'aiuto! – Ci3

+0

.key() è un metodo definito nell'oggetto Event appropriato (probabilmente KeyPressEvent o qualcosa di simile) che restituisce un codice per la chiave che è stata premuta per generare l'evento. – FrankieTheKneeMan

Problemi correlati