Ignitor
Ignitor

Reputation: 3075

How to get a platform native string for a QML Action shortcut?

I have a Qt Quick Controls 2 Action with a shortcut:

Action {
    id: myAction
    shortcut: "Ctrl+D"
}

How can I get a platform native representation of the shortcut?

Here is what I already tried:

Upvotes: 3

Views: 814

Answers (1)

Ignitor
Ignitor

Reputation: 3075

There seems to be no straight forward way to get this.

A workaround is:

  1. Create a disabled Shortcut item
    This will give us the platform native representation via its nativeText property.
  2. Derive from Action and add a custom property to hold the shortcut
    This is necessary because the shortcut property of the Action will always return a string which will be interpreted incorrectly by the Shortcut item when using a StandardKey (the Shortcut item will interpret the integer value as the shortcut so you get a "3" instead of "Ctrl+O").
  3. Bind the custom property to the Action shortcut and to the Shortcut sequence

So in code:

CustomAction.qml

import QtQuick 2.7
import QtQuick.Controls 2.4

Action {
    /* Custom property */
    property var keySequence
    shortcut: keySequence
}

ToolTipButton.qml

import QtQuick 2.7
import QtQuick.Controls 2.4

Button {

    /* Disabled Shortcut */
    Shortcut {
        id: dummyShortcut
        enabled: false
        sequence: action.keySequence
    }

    hoverEnabled: true

    ToolTip.visible: hovered
    ToolTip.delay: 1000
    ToolTip.timeout: 5000
    ToolTip.text: dummyShortcut.nativeText
}

Used like this:

main.qml

import QtQuick 2.7
import QtQuick.Controls 2.4

ApplicationWindow {
    visible: true

    CustomAction {
        id: myAction
        keySequence: StandardKey.Open
    }

    ToolTipButton {
        id: myButton
        action: myAction
        text: "Trigger my action"
    }

}

Upvotes: 2

Related Questions