首页 > 解决方案 > 在 Qt C++ 中定义多个字母的快捷方式

问题描述

我使用以下 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。

标签: c++qt

解决方案


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"; });

推荐阅读