user11376714
user11376714

Reputation: 45

Why can't QML key events be intercepted?

I have the following code:

import QtQuick 2.0

FocusScope {
    anchors.fill: parent
    Keys.onReturnPressed: {
        console.log("++++++++++")
    }
}
import QtQuick 2.9
import QtQuick.Window 2.2

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

    MyTest {
        focus: true
        Keys.onReturnPressed: {
            console.log("==========")
            event.accepted = true
        }
    }
}

The output is:

++++++++++
==========

What is event.accepted = true invalid?

I want to intercept keystroke events in Window and process the event on ly in Window (only output "=========="). How to do that?

Upvotes: 0

Views: 222

Answers (1)

Dimitry Ernot
Dimitry Ernot

Reputation: 6594

You can't disconnect a method when you use onReturnPressed: {} definition.

You have to use Connections for that.

A quick example:

import QtQuick 2.9
import QtQuick.Controls 1.4

Item {
    id: myItem
    anchors.fill: parent

    property bool acceptEvents: true
    signal returnPressed()
    Keys.onReturnPressed: returnPressed()

    Connections {
       id: connection
       target: myItem
       enabled: acceptEvents
       onReturnPressed: {
           console.log("++++++++++")
       }
    }
}


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

    VolumeSlider {
        id: obj
        anchors.fill: parent
        focus: true
        Keys.onReturnPressed: {
            console.log("==========")
            event.accepted = true
        }

        Component.onCompleted: {
            obj.acceptEvents = false; // Remove connections
        }
    }
}

Upvotes: 2

Related Questions