Search code examples
qtqmlqtquick2qt-quick

MouseArea does not pass click to CheckBox


Take a look at this QML snipped:

import QtQuick 2.4
import QtQuick.Controls 2.4

Rectangle {
    
    color: "blue"
    width: 50
    height: 50
    
    CheckBox {
        MouseArea {
            anchors.fill: parent
            propagateComposedEvents: true
        }    
    }
}

I want to add MouseArea over CheckBox so I can handle doubleclick. However no matter how and what I do CheckBox stops working (clicking it won't show checked mark) as soon as there is MouseArea over it.

What's wrong here?


Solution

  • You can programmatically toggle Qt Quick 2 CheckBox with AbstractButton.toggle(). Also, MouseArea propagateComposedEvents property works only with other MouseAreas and not with Qt Quick Controls QML types.

    I don't know your use case so I add few possibilities below.

    Signal connect() method

    Easiest way to achieve toggling through MouseArea is to create signal chain by connecting MouseArea clicked to CheckBox clicked.

    Rectangle {
        anchors.centerIn: parent
        color: "blue"
        width: 50
        height: 50
        CheckBox {
            id: checkBox
            onClicked: toggle()
            MouseArea {
                id: mouseArea
                anchors.fill: parent
            }
            Component.onCompleted: mouseArea.clicked.connect(clicked)
        }
    }
    

    Note that double click always starts with a single click. If you want to catch double clicks with MouseArea you can e.g. use a Timer for preventing propagating clicks to CheckBox.

    Rectangle {
        anchors.centerIn: parent
        color: "blue"
        width: 50
        height: 50
        CheckBox {
            id: checkBox
            MouseArea {
                id: mouseArea
                anchors.fill: parent
                onClicked: {
                    if (timer.running) {
                        return
                    }
                    checkBox.toggle()
                    timer.start()
                }
                Timer {
                    id: timer
                    interval: 250
                    repeat: false
                }
            }
        }
    }
    

    If you want to support CheckBox's pressed visualization and/or if you want to use bigger MouseArea than the size of the CheckBox you can take a look into this answer of the question Can't click button below a MouseArea.