girraiffe
girraiffe

Reputation: 390

How to stop spacebar from triggering a focused QPushButton in PyQt5?

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 , how could I translate it to , but modifying its behavior to what I want?

Upvotes: 4

Views: 954

Answers (2)

andrewf1
andrewf1

Reputation: 61

Setting noFocus policy for button also works. Button stops reacting to spacebar.

self.button= QPushButton()
self.button.setFocusPolicy(Qt.NoFocus)

Upvotes: 0

eyllanesc
eyllanesc

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

Related Questions