问题
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