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
4 replies
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 [doc.qt.nokia.com]. 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:
- {
- if (obj == activeMdiChild()){
- {
- cut();
- qDebug() << "Cut shortcut pressed" << keyEvent->key();
- return true;
- }
- {
- copy();
- qDebug() << "Copy shortcut pressed" << keyEvent->key();
- return true;
- }
- return false;
- } else {
- return false;
- }
- } else {
- // pass the event on to the parent class
- }
- }
That’s correct – key() returns the wrong value. But the Trolls have provided us a pair of nice overloads of operator== [doc.qt.nokia.com] which take a QKeyEvent on one side and a QKeySequence::StandardKey on the other, so you can also write:
- // ...
- }
Just in case you find this nicer than calling matches() (which is called internally anyways).
You must log in to post a reply. Not a member yet? Register here!


