Abolfazl Diyanat
Abolfazl Diyanat

Reputation: 419

Define shortcut with multiple letter in Qt C++

I define a shortcut using following Qt C++ code:

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

How I can define shortcut with multiple letter, for example Ctrl+Shift+S+D+F. If the user hold Ctrl+Shift and press S, D and F in order.

Note: I use Qt 5.15.2 in Linux Ubuntu 20.04.

Upvotes: 2

Views: 253

Answers (1)

Sprite
Sprite

Reputation: 3763

AFAIK, QShortcut currently does not support the feature you are described.

A workaround is to install an event filter yourself.

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

};

And usage:

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

Upvotes: 1

Related Questions