Search code examples
qtpyqtqt-designersignals-slotsqcheckbox

Change checkbox state to not checked when other checkbox is checked pyqt


I'm using Qt Designer and pyqt code to write an app.

I have a very simple question: in my UI I have 2 checkboxes and what I need is to set the first checkbox as always unchecked when the second checkbox is unchecked.

In other words the first checkbox can be checked only when the second checkbox is checked, but the second checkbox can be checked also if the first one is not checked.

In Qt Designer I have not find an easy way to do that with the Signals/Slots function.

I had a look in the Qt API and I tried to write some code:

class CreateRIVLayerDialog(QDialog, FORM_CLASS):
    def __init__(self, iface)

    # some more code here...

    if self.addCheckDB.isChecked():
        self.addCheck.setChecked(False)

but without results.

Does anybody have some hints?

Thanks


Solution

  • The simplest way is with two signal connections, one of which can be done in Qt Designer.

    Your design requires that "the first checkbox can be checked only when the second checkbox is checked". This is equivalent to saying the first checkbox should be disabled when the second checkbox is unchecked. Disabling the checkbox makes it clear to the user that the option is unavailable.

    So in Qt Designer, you should connect the toggled signal of checkbox2 to the setEnabled slot of checkbox1. (It may also be necessary to set the initial enabled state of checkbox1 in Qt Designer as well).

    Then, in your code, you should make a second connection, like this:

        self.checkbox2.toggled.connect(
            lambda checked: not checked and self.checkbox1.setChecked(False))
    

    This will clear the checked state of checkbox1 whenever checkbox2 is unchecked.

    If you wanted to do the whole thing in code, it would look like this:

        self.checkbox1.setEnabled(False)
        self.checkbox2.toggled.connect(self.checkbox1.setEnabled)
        self.checkbox2.toggled.connect(
            lambda checked: not checked and self.checkbox1.setChecked(False))