QML Button - How to check that button is pressed with Control modifier?

Viewed 1436

How we can detect the QML button is clicked (checked) with "Control" key button pressed simultaniously?

3 Answers

AFAIK there's no way to check if the CTRL key is pressed while you're in an onPressed handler of a button, but you could work around that:

Let QML inform you when the CTRL key is pressed/released. Save that status in a property and use it in the onPressed handler of the button.

// Example code
Item {
    id: rootItem

    anchors.fill: parent
    focus: true
    property bool ctrlPressed: false
    Keys.onPressed: {
        if (event.key === Qt.Key_Control) {
            ctrlPressed = true
        }
    }
    Keys.onReleased: {
        if (event.key === Qt.Key_Control) {
            ctrlPressed = false
        }
    }

    Button {
        anchors.centerIn: parent

        text: "Press me"

        onPressed: {
            if (rootItem.ctrlPressed)
                console.log("Click with CTRL")
            else
                console.log("Click without CTRL")
        }
    }
}

This is just a 'workaround' and has some issues:

  • The rootItem has to have the focus
  • when the Application loses focus (ALT+TAB or minimize) while the CTRL button is pressed you might get unexpected behaviour

Another option is simply adding your own MouseArea on top of the button. You could use propogateComposedEvents to allow the Button's default mouse handling to still occur, or you could manually regenerate things like the clicked signal yourself. Neither option is ideal, but maybe one works for you.

Button {
    MouseArea {
        anchors.fill: parent
        propagateComposedEvents: true

        onClicked: {
            if ((mouse.button == Qt.LeftButton) && (mouse.modifiers & Qt.ControlModifier)) {
                doSomething();
            }
        }
    }
}

I used @ParkerHalo's answer. The issue he noticed when the app loses focus with ctrl pressed can be avoided by placing this in the top level Window:

onActiveChanged:  if( ! active )  rootItem.ctrlPressed = false;
Related