How to use QKeySequence or QKeySequenceEdit from QML?

末鹿安然 提交于 2020-12-14 23:57:16

问题


Is it possible to use a QKeySequence or QKeySequenceEdit in QML? I only see the documentation for C++ https://doc.qt.io/qt-5/qkeysequence.html#details

To provide context, I want a QKeySequence to be input by the user of the application so that I can pass it to my C++ backend so that I can hook into native OS APIs and also serialize it to file.

I do not want to actually establish the shortcut within Qt.


回答1:


I created a new object that wraps the QKeySequence::toString and makes it available from QML so I wouldn't have to re-implement a massive switch-case in QML.

#ifndef QMLUTIL_H
#define QMLUTIL_H

#include <QObject>
#include <QKeySequence>

// A singleton object to implement C++ functions that can be called from QML
class QmlUtil : public QObject{
   Q_OBJECT
public:
    Q_INVOKABLE bool isKeyUnknown(const int key) {
        // weird key codes that appear when modifiers
        // are pressed without accompanying standard keys
        constexpr int NO_KEY_LOW = 16777248;
        constexpr int NO_KEY_HIGH = 16777251;
        if (NO_KEY_LOW <= key && key <= NO_KEY_HIGH) {
           return true;
        }

        if (key == Qt::Key_unknown) {
            return true;
        }

        return false;
    }
    Q_INVOKABLE QString keyToString(const int key, const int modifiers){
        if (!isKeyUnknown(key)) {
            return QKeySequence(key | modifiers).toString();
        } else {
            // Change to "Ctrl+[garbage]" to "Ctrl+_"
            QString modifierOnlyString = QKeySequence(Qt::Key_Underscore | modifiers).toString();

            // Change "Ctrl+_" to "Ctrl+..."
            modifierOnlyString.replace("_", "...");
            return modifierOnlyString;
        }
    }
};

To expose this in QML, you have to say engine.rootContext()->setContextProperty("qmlUtil", new QmlUtil()); in your main.cpp where you are setting up your QQmlEngine.

Then you can type qmlUtil.keyToString(event.key, event.modifiers) in QML to turn a keyboard event to a string.

You can combine that with the solution here https://stackoverflow.com/a/64839234/353407 replacing the individual cases with a single function call to qmlUtil.keyToString




回答2:


You can set a string to the sequence property from Shortcut, see Qt docs.

For example if you want to chain Ctrl+M and Ctrl+T, you specify the following:

Shortcut {
    sequence: "cltr+m,ctrl+t"
    onActivated: console.log("you activated turbo mode")
}

It's even possible to assign multiple keyboard shortcuts to the same action, using the sequences (plural) property: Qt docs



来源:https://stackoverflow.com/questions/64826271/how-to-use-qkeysequence-or-qkeysequenceedit-from-qml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!