QML QuickItem鼠标键盘处理

使用QML和C++混合编程,要处理键盘事件,和鼠标事件一样,也是个麻烦事。
键盘事件与鼠标事件的一大不同是,鼠标事件是有坐标的,而键盘事件没有坐标,所以处理鼠标事件的前提是控件获得了焦点(focus)。

QML键盘事件处理

直接上示例:

Rectangle {
    width: 100; height: 100
    focus: true
    Keys.onPressed: {
        if (event.key == Qt.Key_A) {
            console.log('Key A was pressed');
            event.accepted = true;
        }
    }
}

而且,处理键盘事件最好与FocusScope配合,减少手动处理Focus的麻烦。
示例:

//myItem.qml
Rectangle {
    id: window
    color: "white"; width: 240; height: 150
    Column {
        anchors.centerIn: parent; spacing: 15
        MyClickableWidget {
            focus: true             //set this MyWidget to receive the focus
            color: "lightblue"
        }
        MyClickableWidget {
            color: "palegreen"
        }
    }
}
// clickabledWidget.qml
FocusScope {
    id: scope
    //FocusScope needs to bind to visual properties of the children
    property alias color: rectangle.color
    x: rectangle.x; y: rectangle.y
    width: rectangle.width; height: rectangle.height
    Rectangle {
        id: rectangle
        anchors.centerIn: parent
        color: "lightsteelblue"; width: 175; height: 25; radius: 10; antialiasing: true
        Text { id: label; anchors.centerIn: parent }
        focus: true
        Keys.onPressed: {
            if (event.key == Qt.Key_A)
                label.text = 'Key A was pressed'
            else if (event.key == Qt.Key_B)
                label.text = 'Key B was pressed'
            else if (event.key == Qt.Key_C)
                label.text = 'Key C was pressed'
        }
    }
    MouseArea { anchors.fill: parent; onClicked: { scope.focus = true } }
}

效果:

C++部分与鼠标事件基本一致,不再赘述,详情请见QML QQuickItem处理鼠标事件

参考:
https://developer.ubuntu.com/api/qml/sdk-14.10/QtQuick.qtquick-input-focus/
http://stackoverflow.com/questions/34014634/how-to-send-qkeyevent-to-specific-qml-item

你可能感兴趣的:(QtQuick)