Search code examples
qtcheckboxqmlqtquick2qtquickcontrols

"Bind" two QML CheckBoxes together, ensuring their states are always identical


I'd like to create two checkboxes on different pages of a GUI such that they are semantically the "same" checkbox -- same label, same effect. (Having them on both pages is just for the user's convenience.)

This requires "binding" two CheckBox QML elements together such that the state of one is always reflected by the other, and vice-versa.

This is equivalent to what's being asked here, except I'm using QML/JS instead of JS/JQuery.

I thought that a naive implementation of binding the checked state of each checkbox to some global persistent property would work:

// Global shared state object
pragma Singleton
MySharedState {
    my_feature_on: false
}

Then, on two separate pages, the exact same CheckBox instantiation:

// Checkbox implementation (on both pages
CheckBox {
    checked: MySharedState.my_feature_on
    onClicked: MySharedState.my_feature_on = checked
}

However, this doesn't work, because when a checkbox is clicked, it breaks the initial checked binding. This is the intended behavior, not a bug.

So how can I ensure that two checkboxes always share the same "checked" state?

EDIT: According to a comment bellow, the above implementation will work without modification in Qt Quick Controls 2, which was released with Qt 5.7, so this question only applies to prior versions of Qt (including 5.6, which is a "long-term support" release).


Solution

  • When a checkbox is clicked, its' checked property is changed and the original checked: MySharedState.my_feature_on binding is removed. You'll need to create a property binding from Javascript to restore the original binding as explained by J-P Nurmi in the bug report you linked.

    For that, you'll have to use Qt.binding():

    CheckBox {
        checked: MySharedState.my_feature_on
        onClicked: { // the checked binding is removed since checked has been changed externally to the binding
            MySharedState.my_feature_on = checked
            checked = Qt.binding(function() {return MySharedState.my_feature_on}); //we restore the checked binding
        }
    }