Search code examples
qtqmlqtquickcontrols2

Tristate checkbox: deny user from setting it to PartiallyChecked


I have tristate checkbox. I want to be able to set it to Qt.PartiallyChecked from my code, but I do NOT want the user to be able to set it to this state.

This is the workaround I use now:

CheckBox
{
     checkState: allCheckState
     tristate: true
     onClicked: {
          if (checkState == Qt.PartiallyChecked)
               checkState = Qt.Checked;
     }
}

Is there a better solution?


Solution

  • You can override the nextCheckState function. Quoting the documentation:

    This property holds a callback function that is called to determine the next check state whenever the checkbox is interactively toggled by the user via touch, mouse, or keyboard.

    By default, a normal checkbox cycles between Qt.Unchecked and Qt.Checked states, and a tri-state checkbox cycles between Qt.Unchecked, Qt.PartiallyChecked, and Qt.Checked states.

    The nextCheckState callback function can override the default behavior. The following example implements a tri-state checkbox that can present a partially checked state depending on external conditions, but never cycles to the partially checked state when interactively toggled by the user.

    CheckBox {
        tristate: true
        checkState: allChildrenChecked ? Qt.Checked :
                       anyChildChecked ? Qt.PartiallyChecked : Qt.Unchecked
    
        nextCheckState: function() {
            if (checkState === Qt.Checked)
                return Qt.Unchecked
            else
                return Qt.Checked
        }
    }
    

    This QML property was introduced in QtQuick.Controls 2.4 (Qt 5.11).