2

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_())
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Kiril
  • 41
  • 1
  • 7

1 Answers1

3

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):
        ...
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • Hi ekhumoro,"and obj is self" didn't helped. However adding: "return 1" Seems to work :) – Kiril Oct 03 '17 at 16:58
  • @Kiril. It works fine for me on linux. Maybe it works differently on other platforms. The problem with returning `1` (or `True`) is that it will "eat" the event, and any default behaviour will be lot. But maybe that is not an issue in your application. – ekhumoro Oct 03 '17 at 17:03
  • 1
    @Kiril. Just as a matter of interest, can you show the output of `print("Escape key", obj)` using your original example. I would like to try to fix my answer so it works on all platforms. – ekhumoro Oct 03 '17 at 17:06
  • Hi :) --- oh brilliant idea, here we go with **print("Escape key", obj)**: `Escape key Escape key <__main__.MainWindow object at 0x02737A80>` – Kiril Oct 04 '17 at 21:57
  • and with "return 1": `Escape key ` – Kiril Oct 04 '17 at 21:59
  • @Kiril. I don't understand why you are not able to get it to work. If the two objects were really the same, qt would not send two separate events. The `obj is self` **must** work because `self` is definitely not a `QWindow`. Are you sure you're doing a single keypress? – ekhumoro Oct 05 '17 at 00:09
  • Hi, yeah I'm not sure why it didn't work either. Of course single keystroke :) At least is working now. Thank you. I will test soon on Linux / OSX when app is finished. – Kiril Oct 05 '17 at 18:51
  • @Kiril. Okay. Thanks for testing. – ekhumoro Oct 05 '17 at 18:53