Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pyqt

pyqt6

The PyQt6 documentation says that Qt.CheckState.Unchecked == 0 and Qt.CheckState.Checked == 2.

I wrote a little program to test this, but the result is completely different.

Here is the program code:

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

But when I click on the checkbox, the following is displayed:

0
False
2
False
0
False
2
False

Why?


1 Answers

The problem is that you are comparing an int(the value sent by the stateChanged signal) and an enum(Qt.CheckState.Unchecked) so it cannot be compared directly. The solution is to convert the integer to enum:

def print_state(self, state):
    print(Qt.CheckState(state) == Qt.CheckState.Unchecked)
like image 81
eyllanesc Avatar answered Feb 04 '26 11:02

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!