PDA

View Full Version : QAction shortcut does not work for QApplication::sendEvent in QT5



sonulohani
21st November 2016, 13:12
Hi,

I am adding a QAction to a QWidget and trying to trigger the action through the shortcut set to the QAction, by sending a QKeyEvent using QApplication::sendEvent.
The action is not triggered on sending the event, but works fine if I press the key from keyboard.
This happens in qt5.6 but works fine in qt4.6.

the code looks like,


QAction *pAction = new QAction( this );
pAction->setText( tr( "Delete" ) );
pAction->setShortcut( QKeySequence::Delete );
pAction->setShortcutContext( Qt::WidgetWithChildrenShortcut );//tried with other values of the enum also

I add this action to a widget derived from QWidget.

testWidget = new TestWidget();//assume "testwidget" is the pointer holding the TestWidget
testWidget->addActionToWidget( action );//action is added to the widget and connect( action, SIGNAL( triggered() ), SIGNAL( actionInvoked() ) );
testWidget->show();
connect( testWidget , SIGNAL( actionInvoked() ),this, SLOT( actionTriggered() ) );//actionTriggered slot to be called

QKeyEvent keyEvent( QEvent::KeyPress, Qt::Key_Delete, Qt::NoModifier );
QApplication::sendEvent( testAction, &keyEvent );

the slot is not called.

Am I missing something here, since the same piece of code works fine in the Qt4.6.

Thanks

anda_skoa
21st November 2016, 14:44
Have you tried a qWaitForWindowActive() before sending the event?

And/or sending the event to the window or application object?

Cheers,
_