QCheckBox.stateChanged()

Aron Bierbaum aronbierbaum at gmail.com
Wed Oct 12 14:07:17 BST 2022


The QCheckBox.stateChanged() signal [1] is documented to include the state
as an integer. Since QtCore.Qt.CheckState is now an enum.Enum it can not be
compared against the integer value received with the signal. I like the
type safety that comes with using enum.Enum and the stateChanged() signal
is documented to take an integer, but it makes handling the signal more
difficult than it should be.

There seem to be a few different ways that developers can work around this.

 - Convert the integer QtCore.Qt.CheckState(newState)
 - Compare the integer against the enum's value property
QtCore.Qt.CheckState.Checked.value

Is there a better way to handle this? I have attached an example
that should run with PyQt5 and PyQt6.

Regards,
Aron


[1] https://doc.qt.io/qt-6/qcheckbox.html#stateChanged
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20221012/baa4b681/attachment.htm>
-------------- next part --------------
try:
   from PyQt6 import QtCore, QtGui, QtWidgets
except ImportError:
   from PyQt5 import QtCore, QtGui, QtWidgets


def main():
   app = QtWidgets.QApplication([])



   w = QtWidgets.QWidget()
   layout = QtWidgets.QVBoxLayout()
   w.setLayout(layout)
   check = QtWidgets.QCheckBox("Does this work?")
   layout.addWidget(check)
   label1 = QtWidgets.QLabel("")
   layout.addWidget(label1)
   label2 = QtWidgets.QLabel("")
   layout.addWidget(label2)
   label3 = QtWidgets.QLabel("")
   layout.addWidget(label3)

   def onCheckStateChanged(newState):
      label1.setText("'%s' '%s'" % (type(newState), newState))
      state = check.checkState()
      label2.setText("'%s' '%s'" % (type(state), state))
      label3.setText("equal: %s" % (newState == state))

   check.stateChanged.connect(onCheckStateChanged)

   w.show()

   app.exec()


if __name__ == "__main__":
   main()


More information about the PyQt mailing list