When the space key is pressed, I want the button to not trigger; how can I implement that functionality? I have found a similar post but it is written in c++, how could I translate it to python, but modifying its behavior to what I want?
If you want any keyboard event that triggers the button then just implement an event filter:
import sys
from PyQt5 import QtCore, QtWidgets
class Listener(QtCore.QObject):
def __init__(self, button):
super().__init__(button)
self._button = button
self.button.installEventFilter(self)
@property
def button(self):
return self._button
def eventFilter(self, obj, event):
if obj is self.button and event.type() == QtCore.QEvent.KeyPress:
return True
return super().eventFilter(obj, event)
App = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
lay = QtWidgets.QVBoxLayout(w)
btn = QtWidgets.QPushButton()
lay.addWidget(btn)
w.show()
btn.clicked.connect(print)
listener = Listener(btn)
sys.exit(App.exec())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With