keyPressEvent方法在这个程序中如何工作?
问题描述:
我无法理解keyPressEvent方法在此程序中的工作方式。具体来说,这里的“e”是什么? keyPressEvent是使用预先存在的实例“e”的重新定义的方法吗?keyPressEvent方法在这个程序中如何工作?
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()被拉到事件处理程序中),以便我们可以组合相关事件并处理它们一个功能。
# 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.
我对事件处理程序不是很熟悉,但我猜测key()是在Qt中定义的?然后当一个键被按下时,它传递给这个功能。谢谢您的帮助! – Ci3
.key()是在适当的Event对象(可能是KeyPressEvent或类似的东西)中定义的一种方法,它返回被按下来生成事件的密钥的代码。 – FrankieTheKneeMan