在 Qt C++ 中用多个字母定义快捷方式

时间:2021-01-24 07:01:30

标签: c++ qt

我使用以下 Qt C++ 代码定义了一个快捷方式:

QShortcut *shortcut = new QShortcut(QKeySequence("Ctrl+Shift+S"), this);
QObject::connect(shortcut, &QShortcut::activated, [=]{qDebug()<<"Example";});

如何使用多个字母定义快捷方式,例如 Ctrl+Shift+S+D+F。如果用户按住 Ctrl+Shift 并按顺序按 SDF

注意:我在 Linux Ubuntu 20.04 中使用 Qt 5.15.2。

1 个答案:

答案 0 :(得分:1)

AFAIK,QShortcut 目前不支持您所描述的功能。

一种解决方法是自己安装事件过滤器。

#include <QCoreApplication>
#include <QKeyEvent>
#include <QVector>


class QMultipleKeysShortcut : public QObject
{
    Q_OBJECT

public:
    explicit inline QMultipleKeysShortcut(const QVector<int> &Keys, QObject *pParent) :
        QObject{pParent}, _Keys{Keys}
    {
        pParent->installEventFilter(this);
    }

Q_SIGNALS:
    void activated();

private:
    QVector<int> _Keys;
    QVector<int> _PressedKeys;

    inline bool eventFilter(QObject *pWatched, QEvent *pEvent) override
    {
        if (pEvent->type() == QEvent::KeyPress)
        {
            if (_PressedKeys.size() < _Keys.size())
            {
                int PressedKey = ((QKeyEvent*)pEvent)->key();

                if (_Keys.at(_PressedKeys.size()) == PressedKey) {
                    _PressedKeys.append(PressedKey);
                }
            }
            if (_PressedKeys.size() == _Keys.size()) {
                emit activated();
            }
        }
        else if (pEvent->type() == QEvent::KeyRelease)
        {
            int ReleasedKey = ((QKeyEvent*)pEvent)->key();

            int Index = _PressedKeys.indexOf(ReleasedKey);
            if (Index != -1) {
                _PressedKeys.remove(Index, _PressedKeys.size() - Index);
            }
        }

        return QObject::eventFilter(pWatched, pEvent);
    }

};

和用法:

QMultipleKeysShortcut *pMultipleKeysShortcut = new QMultipleKeysShortcut{{Qt::Key_Control, Qt::Key_Shift, Qt::Key_S, Qt::Key_D, Qt::Key_F}, this};
connect(pMultipleKeysShortcut, &QMultipleKeysShortcut::activated, [=] {qDebug() << "Example"; });
相关问题