I have the following code:

  • MyTest.qml
import QtQuick 2.0

FocusScope {
    anchors.fill: parent
    Keys.onReturnPressed: {
        console.log("++++++++++")
    }
}
  • main.qml
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?

1 Answers

2
Romha Korev On

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
        }
    }
}