Reputation: 390
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?
Upvotes: 4
Views: 954
Reputation: 61
Setting noFocus policy for button also works. Button stops reacting to spacebar.
self.button= QPushButton()
self.button.setFocusPolicy(Qt.NoFocus)
Upvotes: 0
Reputation: 243897
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())
Upvotes: 4