Python PyQt5 - QEvent Keypress executes double times

人盡茶涼 提交于 2019-12-11 04:38:39

问题


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):
        ...


来源:https://stackoverflow.com/questions/46543792/python-pyqt5-qevent-keypress-executes-double-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!