Last active
August 29, 2015 14:24
-
-
Save anunyin/98106b80ef548274c138 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "shortcut.h" | |
#include <QKeyEvent> | |
#include <QCoreApplication> | |
#include <QDebug> | |
Shortcut::Shortcut(QObject *parent) | |
: QObject(parent) | |
, m_keySequence() | |
, m_keypressAlreadySend(false) | |
{ | |
qApp->installEventFilter(this); | |
} | |
void Shortcut::setKey(QVariant key) | |
{ | |
QKeySequence newKey = key.value<QKeySequence>(); | |
if(m_keySequence != newKey) { | |
m_keySequence = key.value<QKeySequence>(); | |
emit keyChanged(); | |
} | |
} | |
bool Shortcut::eventFilter(QObject *obj, QEvent *e) | |
{ | |
if(e->type() == QEvent::KeyPress && !m_keySequence.isEmpty()) { | |
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(e); | |
// Just mod keys is not enough for a shortcut, block them just by returning. | |
if (keyEvent->key() >= Qt::Key_Shift && keyEvent->key() <= Qt::Key_Alt) { | |
return QObject::eventFilter(obj, e); | |
} | |
int keyInt = keyEvent->modifiers() + keyEvent->key(); | |
// The m_keypressAlreadySend seems redundant because of ->isAutoRepeat(), | |
// however without it, multiple events are still sent for each press/release. | |
if(QKeySequence(keyInt) == m_keySequence) { | |
if (keyEvent->isAutoRepeat()) | |
emit pressedAndHold(); | |
else if (!m_keypressAlreadySend) | |
{ | |
m_keypressAlreadySend = true; | |
emit pressed(); | |
} | |
} | |
e->accept(); | |
} | |
else if(e->type() == QEvent::KeyRelease) { | |
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(e); | |
if (!keyEvent->isAutoRepeat() && m_keypressAlreadySend) | |
{ | |
m_keypressAlreadySend = false; | |
emit released(); | |
} | |
e->accept(); | |
} | |
return QObject::eventFilter(obj, e); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <QObject> | |
#include <QKeySequence> | |
#include <QVariant> | |
class Shortcut : public QObject | |
{ | |
Q_OBJECT | |
Q_PROPERTY(QVariant key READ key WRITE setKey NOTIFY keyChanged) | |
public: | |
explicit Shortcut(QObject *parent = 0); | |
void setKey(QVariant key); | |
QVariant key() { return m_keySequence; } | |
bool eventFilter(QObject *obj, QEvent *e); | |
signals: | |
void keyChanged(); | |
void pressed(); | |
void released(); | |
void pressedAndHold(); | |
public slots: | |
private: | |
QKeySequence m_keySequence; | |
bool m_keypressAlreadySend; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment