QML CheckBox复选框详解

1.简介

CheckBox提供了一个选项按钮,可以打开(选中)或关闭(未选中)。复选框通常用于从一组选项中选择一个或多个选项

常用属性:

  • checked :bool  :选中
  • tristate : bool :复选框是否为三状态复选框
  • nextCheckState : function :此属性包含一个回调函数,每当用户通过触摸、鼠标或键盘以交互方式切换复选框时,该回调函数将被调用以确定下一个检查状态。

2.示例

示例1:实现自我排他,任意时刻只能选中一个checkBox。使用ButtonGroup,将CheckBox放到group中,设置exclusive属性为true。

Window {
    visible: true
    width: 400
    height: 400
    title: qsTr("Hello World")

    ButtonGroup{
        id:group
        exclusive: true
        buttons: col.children
    }

    Column{
        id:col
        CheckBox {
            id:ch1
            checked: true
            text: qsTr("First")
        }
        CheckBox {
            id:ch2
            text: qsTr("Second")
        }
        CheckBox {
            id:ch3
            checked: true
            text: qsTr("Third")
        }
    }
}

示例2:三状态复选框。

Window {
    visible: true
    width: 400
    height: 400
    title: qsTr("Hello World")

    Column {
        ButtonGroup {
            id: childGroup
            exclusive: false
            checkState: parentBox.checkState
        }

        CheckBox {
            id: parentBox
            text: qsTr("Parent")
            checkState: childGroup.checkState
        }

        CheckBox {
            checked: true
            text: qsTr("Child 1")
            leftPadding: indicator.width
            ButtonGroup.group: childGroup
        }

        CheckBox {
            text: qsTr("Child 2")
            leftPadding: indicator.width
            ButtonGroup.group: childGroup
        }
    }
}

示例3:设置三状态复选框的选中顺序。

改变check的顺序,使用nextCheckState回调

Window {
    visible: true
    width: 400
    height: 400
    title: qsTr("Hello World")

    CheckBox {
        tristate: true

        nextCheckState: function() {
            if (checkState === Qt.Unchecked)
                return Qt.Checked
            else if (checkState === Qt.Checked)
                return Qt.PartiallyChecked
            else
                 return Qt.Unchecked
        }
    }
}

猜你喜欢

转载自blog.csdn.net/wzz953200463/article/details/129369338