Come utilizzare QKeySequence o QKeySequenceEdit da QML?
È possibile utilizzare QKeySequence o QKeySequenceEdit in QML? Vedo solo la documentazione per C ++https://doc.qt.io/qt-5/qkeysequence.html#details
Per fornire il contesto, desidero che un QKeySequence venga inserito dall'utente dell'applicazione in modo da poterlo passare al mio backend C ++ in modo da poterlo collegare alle API del sistema operativo native e serializzarlo anche su file.
Non voglio stabilire effettivamente il collegamento all'interno di Qt.
Risposte
Ho creato un nuovo oggetto che avvolge QKeySequence::toStringe lo rende disponibile da QML in modo da non dover reimplementare un massiccio 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;
}
}
};
Per esporre questo in QML, devi dire engine.rootContext()->setContextProperty("qmlUtil", new QmlUtil());nel tuo main.cppdove stai impostando il tuo QQmlEngine.
Quindi puoi digitare qmlUtil.keyToString(event.key, event.modifiers)QML per trasformare un evento della tastiera in una stringa.
Puoi combinarlo con la soluzione qui https://stackoverflow.com/a/64839234/353407 sostituire i singoli casi con una singola chiamata di funzione a qmlUtil.keyToString
È possibile impostare una stringa per la sequenceproprietà da Shortcut, vedere la documentazione Qt .
Ad esempio, se vuoi concatenare Ctrl+ Me Ctrl+ T, specifica quanto segue:
Shortcut {
sequence: "cltr+m,ctrl+t"
onActivated: console.log("you activated turbo mode")
}
È anche possibile assegnare più scorciatoie da tastiera alla stessa azione, utilizzando la sequencesproprietà (plurale): Qt docs