How to catch actions with default shortcuts
-
Hello,
In my QTextEdit editor application I have defined a 'cut' action with a ctrl+x shortcut.
The problem is that although the shortcut works, it seems to be bypassing the slot defined in my application.
When I select the action from the menu or the toolbar button, the debugger will break in the slot function it is connected to. When I press ctrl+x, text is cut from the editor to the clip board, but the debugger does not break.
If I redefine the shortcut to , say, ctrl+b, the debugger will break, so I assume the code is correct.
It seems that ctrl+x is a special case which bypasses the action but operates directly on the QTextedit object.
How can I force ctrl+x to trigger the cut action?Best regards,
PAul
-
Ctrl-X (or better the key sequence behind QKeySequence::Cut) is handled directly in the the key event handler of the text edit. You can intercept it by installing an "eventFilter":http://doc.qt.nokia.com/4.7/qobject.html#eventFilter. The sample code in the link happens by chance to show you this case with a similar key :)
-
Thanks for your help. I had found that page but was wondering if that was the proper way to handle this.
Of course the code didn't work out of the box, mainly because ctrl+x isn't a key, but a key sequence, which requires a call to keyEvent->matches() instead of equation with keyEvent->key
Below is my adaptation of the code for key sequences:@bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == activeMdiChild()){
if (event->type() == QEvent::KeyPress) {
QKeyEvent keyEvent = static_cast<QKeyEvent>(event);
if (keyEvent->matches(QKeySequence::Cut))
{
cut();
qDebug() << "Cut shortcut pressed" << keyEvent->key();
return true;
}
if (keyEvent->matches(QKeySequence::Copy))
{
copy();
qDebug() << "Copy shortcut pressed" << keyEvent->key();
return true;
}
return false;
} else {
return false;
}
} else {
// pass the event on to the parent class
return QMainWindow::eventFilter(obj, event);
}
}
@ -
That's correct - key() returns the wrong value. But the Trolls have provided us a pair of nice overloads of "operator==":http://doc.qt.nokia.com/4.7/qkeyevent.html#operator-eq-eq which take a QKeyEvent on one side and a QKeySequence::StandardKey on the other, so you can also write:
@
if(keyEvent == QKeySequence::Copy) {
// ...
}
@Just in case you find this nicer than calling matches() (which is called internally anyways).