Search code examples
pythonpyqtpyqt5qcheckbox

Is the a way to check a QCheckBox with a key press?


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.


Solution

  • 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_())