【问题标题】:Is the a way to check a QCheckBox with a key press?是一种通过按键检查 QCheckBox 的方法吗?
【发布时间】:2019-09-14 11:11:40
【问题描述】:

我在 PyQt5 中工作,希望能够像使用 QPushButton 一样在按键上选中/取消选中 QCheckBox。我已经检查了文档和谷歌,但找不到这样做的方法。

【问题讨论】:

  • 当你说能够像使用 QPushButton 一样按下按钮来选中/取消选中 QCheckBox,你的意思是当 QPushButton 所在的位置必须有 1 个 QPushButton + 1 个 QCheckBox按下 QCheckBox 更改状态,对吗?
  • 不,我只是希望能够在按键时选中/取消选中 QCheckBox。
  • 按钮按下:能够像使用 QPushButton 一样通过按钮按下来选中/取消选中 QCheckBox 或按键:能够在按键上选中/取消选中 QCheckBox .?
  • 如果 QCheckBox 处于焦点位置但未选中,我按下一个键让我们说“Enter”,我希望 QCheckBox 被选中。

标签: python pyqt pyqt5 qcheckbox


【解决方案1】:

你必须重写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("StackOverflow")
    w.show()
    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-26
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多