Joseph Joseph - 4 months ago 17
Python Question

QCheckBox only executes when checked twice

I have a QCheckBox (

deselect_checkbox
) which, when checked, sets another QCheckBox (
first_checkbox
) and itself to
False
. However, it only works every other time and I'm not sure why. Here is the code:

def deselect_func():
if self.dockwidget.deselect_checkbox.isChecked():
self.dockwidget.first_checkbox.setChecked(False)
self.dockwidget.deselect_checkbox.setChecked(False)

self.dockwidget.deselect_checkbox.stateChanged.connect(deselect_func)


How can I get the function to run everytime I check
deselect_checkbox
?




Using QGIS 2.16.0 with Qt Designer 4.8.5.

Answer

You're mixing up "check-state" and "checked".

The former can have three states: Unchecked, PartiallyChecked, and Checked, whereas the latter is just True/False. If you call setChecked() instead of setCheckState(), a state-change won't be registered. Thus, on the next click, a stateChanged signal won't be emitted (because no change is detected).

To fix this, your code therefore must either look like this:

def deselect_func():
    if self.dockwidget.deselect_checkbox.isChecked():
        self.dockwidget.first_checkbox.setChecked(False)
        self.dockwidget.deselect_checkbox.setChecked(False)

self.dockwidget.deselect_checkbox.toggled.connect(deselect_func)

or like this:

def deselect_func():
    if self.dockwidget.deselect_checkbox.checkState() == QtCore.Qt.Checked:
        self.dockwidget.first_checkbox.setCheckState(QtCore.Qt.Unchecked)
        self.dockwidget.deselect_checkbox.setCheckState(QtCore.Qt.Unchecked)

self.dockwidget.deselect_checkbox.stateChanged.connect(deselect_func)

But note that this means deselect_checkbox will never been shown as checked, since it is always immediately unchecked. Is that what you really intended?