QML QuickItemマウスキーボード処理

3720 ワード

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 QQQQQuickItemを参照してマウスイベントを処理してください.
参照先: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