QAction shortcut doesnt always work

懵懂的女人 提交于 2019-12-06 19:09:21

问题


I have a Qaction on a menu item for deleting selected items in one of my views. Here is how i create the action:

deleteAct = new QAction( tr("Delete Selected"), this);
deleteAct->setShortcut(QKeySequence::Delete);
connect(deleteAct, SIGNAL(triggered()), this, SLOT(deleteSelected()));  

I setup a keyboard shortcut (Delete Key) which should trigger the delectAct action. It works most of the time but at some points it stops working... Does anyone know why the shortcut would stop working?

Note: the action still works if i trigger it from the menu item. Its just the shortcut that doesn't...


回答1:


You need to add the action to a widget, since it's the widget that will be listening for key events. Assuming "this" is a mainwindow, simply do

addAction(deleteAct);

Note that you can add the same action to multiple widgets (that's the whole point of the separated action concept). So it's fine to add it to the mainwindow and to a menu.




回答2:


Try changing the shortcut context of the action, for example:

deleteAct->setShortcutContext(Qt::ApplicationShortcut);



回答3:


Without seeing the complete code, I'd hazard a guess that somewhere it gets enabled/disabled. Make sure that the shortcut is getting hit in the constructor and not 'disabled' somewhere else because of a setting perhaps.




回答4:


You can use http://doc.qt.io/qt-5/qaction.html#shortcutVisibleInContextMenu-prop property since QT 5.10 for this:

deleteAct->setShortcutVisibleInContextMenu(true);


来源:https://stackoverflow.com/questions/9319407/qaction-shortcut-doesnt-always-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!