Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Qt QShortcut with numpad key

QShortcut makes it easy to connect a QShortcutEvent (Key press, combination or sequence) to a slot method, e.g.:

QShortcut *shortcut = new QShortcut( QKeySequence(Qt::Key_7), this, 0, 0, Qt::ApplicationShortcut);

(Hint: for number keys, a QSignalMapper can be used to map the QShortcut's activated() signal to a Slot with int parameter).

However, in this example, with NumLock (numpad enabled), both '7' keys will trigger the Shortcut's activated() signal.

Is there a way to detect the different keys other than filtering or reimplementing a widget's keyPressEvent and check QKeyEvent::modifiers() for Qt::KeypadModifier?

Digging further, I found

QTBUG-20191 Qt::KeypadModifier does not work with setShortcut linking to a patch that has been merged into 4.8 in Sept. 2012 and which comes with a test case using

button2->setShortcut(Qt::Key_5 + Qt::KeypadModifier);

which does not work for my QShortcut on Qt 4.8.1, i.e. neither of the '7' keys are recognized using (adding) the modifier flag.

So I guess the quickest way would be installing a filter to detect the modifier and let all other keyEvents be handled by the default implementation to be useable with QShortcut?

like image 643
handle Avatar asked Jul 18 '13 08:07

handle


2 Answers

You can use Qt.KeypadModifier, For example [Python]:

def keyPressEvent(self, event):
    numpad_mod = int(event.modifiers()) & QtCore.Qt.KeypadModifier
    if event.key() == QtCore.Qt.Key5 and numpad_mod:
        #Numpad 5 clicked
like image 164
Aviad Avatar answered Oct 21 '22 18:10

Aviad


For this you can use keyReleaseEvent(QKeyEvent *event) For example

void Form::keyReleaseEvent(QKeyEvent *event)    {
    int key = event->nativeScanCode();

    if( key == 79 ) //value for numpad 7
    {
       //your statement   
    }


}
like image 2
reggie Avatar answered Oct 21 '22 18:10

reggie