Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 318
girraiffe Avatar asked Oct 14 '25 14:10

girraiffe


1 Answers

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())
like image 88
eyllanesc Avatar answered Oct 17 '25 03:10

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!