Python PyQt5-QEvent Keypress执行两次 [英] Python PyQt5 - QEvent Keypress executes double times

查看:729
本文介绍了Python PyQt5-QEvent Keypress执行两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当ESC键按下PRINTS时,我有这个简单的代码,但是似乎执行了两次"而不是只触发一次. Python 3.6.2 x86 + PyQt 5.9

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_())

推荐答案

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

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

这篇关于Python PyQt5-QEvent Keypress执行两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆