1

I'm working in PyQt5 and would like to be able check/uncheck a QCheckBox on a key prespress like with a QPushButton. I've checked the documentation and Google but cannot find a way to do this.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
user8565662
  • 127
  • 1
  • 1
  • 6
  • When you say *able to check / uncheck to QCheckBox with a button press like with a QPushButton*, you mean that there must be 1 QPushButton + 1 QCheckBox where when the QPushButton is pressed the QCheckBox changes state, am I right? – eyllanesc Apr 25 '19 at 05:16
  • No, I simply want to be able check/uncheck a QCheckBox on a key press. – user8565662 Apr 25 '19 at 05:27
  • button press: *able to check/uncheck a QCheckBox with a button press like with a QPushButton* or key press: *able check/uncheck a QCheckBox on a key press.*? – eyllanesc Apr 25 '19 at 05:30
  • If a QCheckBox is in focus but not checked and I press a key lets say 'Enter' I want the QCheckBox to be checked. – user8565662 Apr 25 '19 at 05:33

1 Answers1

1

You have to overwrite the keyPressEvent method and call the nextCheckState() method to change the state of the QCheckBox:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets


class CheckBox(QtWidgets.QCheckBox):
    def keyPressEvent(self, event):
        if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
            self.nextCheckState()
        super(CheckBox, self).keyPressEvent(event)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = CheckBox("StackOverflow")
    w.show()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241