How to set shotcut combined key about TextArea?

114 Views Asked by At

I want to insert a string inside a TextArea when I press key combinations such as ctrl+a or ctrl+s or ctrl+c.

I've written some code, but it doesn't work.

example.qml

Rectangle {
    width: 100; height: 100
    focus: true
    Keys.onPressed: {
        if(event.modifiers && Qt.ControlModifier) {
            if(event.key === Qt.Key_A) {
                console.log('select all')
                event.accepted = true;
            }
            else if(event.key === Qt.Key_S) {
                console.log('save')
                event.accepted = true;
            }
        }
    }



    TextArea {
        id: textArea
        text:""
        wrapMode: TextEdit.Wrap
        font.pointSize: 16
        anchors.fill: parent

        property bool isModify:false
        property string path:""

        style: TextAreaStyle {
            textColor: "#333"
            selectionColor: "steelblue"
            selectedTextColor: "#eee"
            backgroundColor: "#eee"
        }

    }
}
1

There are 1 best solutions below

0
On

Move your Keys.onPressed block inside the TextArea element in order to receive events, just like this:

import QtQuick 2.4
import QtQuick.Controls 1.3

TextArea
{
    id: textArea
    anchors.fill: parent

    Keys.onPressed:
    {
        if (event.modifiers == Qt.ControlModifier)
        {
            switch (event.key)
            {
                case Qt.Key_A:
                {
                    console.log("select")
                    event.accepted = true
                    break
                }
                case Qt.Key_S:
                {
                    console.log("save")
                    event.accepted = true
                    break
                }
                default:
                    event.accepted = false
            }
        }
    }
}

Edit

Also to provide a minimum of explanation: In your case the surrounding Rectangle would handle keypress events - only as long as its focus is set. When you start typing inside your TextArea (it now has the focus) you're bypassing the key handler. Instead of setting/resetting the focus it's easier to let the TextArea handle all the key events.

Hope this helps!