user8565662
user8565662

Reputation: 127

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.

Upvotes: 1

Views: 616

Answers (1)

eyllanesc
eyllanesc

Reputation: 243907

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

Upvotes: 1

Related Questions