QML2 ApplicationWindow Keys handling

2019-06-20 18:36发布

问题:

Is there any way to handle key press events in ApplicationWindow of QtQuick.Controls component? Documentation of Qt5.3 does not provide any way to do this. Also, it says that Keys is only exists in Item-objects . When I try to handle key press event it says "Could not attach Keys property to: ApplicationWindow_QMLTYPE_16(0x31ab890) is not an Item":

import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.1
import QtQuick.Window 2.1


ApplicationWindow {
    id: mainWindow
    visible: true
    width: 720
    height: 405
    flags: Qt.FramelessWindowHint
    title: qsTr("test")

    x: (Screen.width - width) / 2
    y: (Screen.height - height) / 2

    TextField {
        id: textField
        x: 0
        y: 0
        width: 277
        height: 27
        placeholderText: qsTr("test...")
    }

    Keys.onEscapePressed: {
        mainWindow.close()

        event.accepted = true;
    }
}

回答1:

ApplicationWindow {
id: mainWindow
  Item {
    focus: true
    Keys.onEscapePressed: {
      mainWindow.close()
      event.accepted = true;
    }
  TextField {}
  }
}


回答2:

Maybe this will help some. Using a Shortcut doesn't require focus to be set.

ApplicationWindow {
    id: mainWindow

    Shortcut {
        sequence: "Esc"
        onActivated: mainWindow.close()
        }
    }
}