我有这个简单的代码,当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_())
答案 0 :(得分:2)
QApplication
上安装的事件过滤器将接收应用程序中所有对象的事件。因此,您需要检查obj
参数以过滤掉您不感兴趣的对象中的事件。
在您的示例中,您可能只想要主窗口中的事件。所以你可以像这样解决它:
def eventFilter(self, obj, event):
if (event.type() == QtCore.QEvent.KeyPress and obj is self):
...