Reputation: 115
So I have the following basic window, my issue is that whenever I press the tab button once it triggers the event twice. Printing "tab" and "keypress" twice. I looked around and all I found about this issue was a C++ answer, I tried to understand the solution but was unable too.
from PyQt5 import QtCore, QtWidgets
class MyWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MyWindow, self).__init__(self)
# Install the event filter that will be used later to detect key presses
QtWidgets.qApp.installEventFilter(self)
self.button = QtGui.QPushButton('Test', self)
self.button.clicked.connect(self.handleButton)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.button)
def handleButton(self):
print("Button")
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.KeyPress:
print("keypress")
if event.key() == QtCore.Qt.Key_Escape:
self.close()
if event.key() == QtCore.Qt.Key_Tab:
print("Tab")
pass
return super(ItemPrice, self).eventFilter(obj, event)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
Upvotes: 2
Views: 2563
Reputation: 13317
The eventFilter()
method needs a boolean result, or 0/1, to return if an event is relevant or not (the filter part). When you return False
the event is not blocked, and will hit his target, this lets the application handle the event in a normal way.
In your example, when an expected key is pressed (this is a relevant event), you need to return 1
or True
to "intercept" it and prevent the program to handle it, since you provide your own process. In the other cases, you can call the super method like you did :
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.KeyPress:
print("keypress")
if event.key() == QtCore.Qt.Key_Escape:
self.close()
return 1
if event.key() == QtCore.Qt.Key_Tab:
print("Tab")
return 1
return super().eventFilter(obj, event)
Upvotes: 3