Python PyQt5 - QEvent Keypress executes double tim

2019-08-12 11:11发布

问题:

I have this simple code, when ESC key pressed PRINTS, however it seems executing "double" times instead of firing one-time only. Python 3.6.2 x86 + PyQt 5.9

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys

from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5 import QtCore, QtGui, QtWidgets


class MainWindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        qApp.installEventFilter(self) #keyboard control

    def eventFilter(self, obj, event):
        if (event.type() == QtCore.QEvent.KeyPress):
            key = event.key()

            if key == Qt.Key_Escape:
                print("Escape key")

        return super(MainWindow, self).eventFilter(obj, event)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

回答1:

An event-filter installed on the QApplication will receive events for all objects in the application. So you need to check the obj argument to filter out events from objects you are not interested in.

In your example, you probably only want events from your main window. So you can fix it like this:

def eventFilter(self, obj, event):
    if (event.type() == QtCore.QEvent.KeyPress and obj is self):
        ...