有没有一种方法可以通过按键来检查 QCheckBox?

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

我在 PyQt5 中工作,希望能够 check/uncheck 按键上的 QCheckBox,就像使用 QPushButton 一样。我已经检查了文档和 Google 但找不到执行此操作的方法。

你必须覆盖keyPressEvent方法并调用nextCheckState()方法来改变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("Whosebug")
    w.show()
    sys.exit(app.exec_())