PyQt4重写事件处理方法

PyQt中的事件处理主要以来重写事件处理函数来实现。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui, QtCore 

class Escape(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self)
        
        self.setWindowTitle('escape')
        self.resize(250, 150)
        self.connect(self, QtCore.SIGNAL('closeEmitApp()'),
                            QtCore.SLOT('close()'))
    
    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()
            
app = QtGui.QApplication(sys.argv)
escape = Escape()
escape.show()
sys.exit(app.exec_())            

在上面的示例中,我们重新实现了keyPressEvent()事件处理方法。

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()

通过上面的方法,当我们按下ESC键时程序就会结束。

原文地址:https://www.cnblogs.com/moonlightpoet/p/5346767.html