Python PyQt5 - QEvent Keypress 执行两次

标签 python events pyqt pyqt5 keypress

我有这个简单的代码,当 ESC 键按下 PRINTS 时,它似乎执行“两次”而不是仅触发一次。 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_())

最佳答案

安装在QApplication上的事件过滤器将接收应用程序中所有对象的事件。因此,您需要检查 obj 参数以过滤掉您不感兴趣的对象中的事件。

在您的示例中,您可能只需要主窗口中的事件。所以你可以像这样修复它:

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

关于Python PyQt5 - QEvent Keypress 执行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46543792/

相关文章:

Python:SettingWithCopyWarning:试图在 DataFrame 的切片副本上设置一个值

python - DJANGO_SETTINGS_MODULE 已定义,项目设置通过 `python manage.py ` 导入,但 django-pytest 找不到 django 设置

python - 用简单的 Python 脚本测试计算机处理速度

c# - 如何从PropertyChanged事件获取Type?

qt - 如何实现基于树的 QComboBox

qt - qfiledialog - 过滤文件夹?

python - 如何在 VSCode 中使用远程 Jupyter 服务器?

python - PIP 安装和 Python 路径

c# - ASP.NET:通过 Intellisense 的 Page_Events 列表?我怎么知道签名?

javascript - 如何等到点击函数内部?