为什么不能截获QML键事件?

时间:2019-05-13 09:35:17

标签: qt qml

我有以下代码:

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

输出为:

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

什么是event.accepted = true无效?

我想截获Window中的击键事件并仅在Window中处理该事件(仅输出“ ==========”)。该怎么做?

1 个答案:

答案 0 :(得分:2)

使用onReturnPressed: {}定义时无法断开方法。

您必须为此使用Connections

一个简单的例子:

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