QML에서 QKeySequence 또는 QKeySequenceEdit를 사용하는 방법은 무엇입니까?

Nov 13 2020

QML에서 QKeySequence 또는 QKeySequenceEdit를 사용할 수 있습니까? C ++에 대한 설명서 만 표시됩니다.https://doc.qt.io/qt-5/qkeysequence.html#details

컨텍스트를 제공하기 위해 애플리케이션 사용자가 QKeySequence를 입력하여 C ++ 백엔드로 전달하여 네이티브 OS API에 연결하고 파일로 직렬화 할 수 있도록합니다.

Qt에서 실제로 바로 가기를 설정하고 싶지 않습니다.

답변

1 Mark Nov 16 2020 at 17:41

을 감싸고 QKeySequence::toStringQML에서 사용할 수 있도록 하는 새 객체를 만들었 으므로 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;
        }
    }
};

QML이 노출하려면 말을 engine.rootContext()->setContextProperty("qmlUtil", new QmlUtil());당신의 main.cpp당신이 당신의 QQmlEngine를 설정하는 곳.

그런 다음 qmlUtil.keyToString(event.key, event.modifiers)QML을 입력 하여 키보드 이벤트를 문자열로 바꿀 수 있습니다 .

여기에서 솔루션과 결합 할 수 있습니다. https://stackoverflow.com/a/64839234/353407 개별 케이스를 단일 함수 호출로 대체 qmlUtil.keyToString

Amfasis Nov 13 2020 at 19:07

에서 sequence속성에 문자열을 설정할 수 있습니다 ( Qt 문서Shortcut 참조) .

예를 들어 Ctrl+ MCtrl+ 를 연결 T하려면 다음을 지정합니다.

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

sequences(복수) 속성을 사용하여 동일한 작업에 여러 키보드 단축키를 할당 할 수도 있습니다 . Qt docs