Qt.CheckState.Checked != 2 和 Qt.CheckState.Checked != 0

Qt.CheckState.Checked != 2 and Qt.CheckState.Checked != 0

PyQt6 文档说 Qt.CheckState.Unchecked == 0Qt.CheckState.Checked == 2

我写了一个小程序来测试这个,但是结果完全不同。

程序代码如下:

from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QApplication, QMainWindow, QCheckBox


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setWindowTitle("My App")

        self.widget = QCheckBox("CB")
        self.widget.setCheckState(Qt.CheckState.Checked)
        self.widget.stateChanged.connect(self.print_state)

        self.setCentralWidget(self.widget)

    def print_state(self, state):
        print(state)
        print(state == Qt.CheckState.Unchecked)


if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()

但是当我点击复选框时,显示如下:

0
False
2
False
0
False
2
False

为什么?

问题是您正在比较一个整数(stateChanged 信号发送的值)和一个枚举(Qt.CheckState.Unchecked),因此无法直接比较。解决方案是将整数转换为枚举:

def print_state(self, state):
    print(Qt.CheckState(state) == Qt.CheckState.Unchecked)