以下示例重现了您的错误。我还在 Qt 框架中进行了调试,并逐步完成了QMenu::keyPressEvent
and QAction::event
,但似乎没有正确处理按下的键。
在QAction::event
事件类型中QEvent::Shortcut
永远不会发生。作为一种解决方法,我建议您从自己的函数派生QAction
并实现自己的event
函数。
#include <QApplication>
#include <QFrame>
#include <QMenu>
#include <QAction>
#include <QDebug>
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
QApplication::setAttribute(Qt::ApplicationAttribute::AA_DontShowShortcutsInContextMenus,false);
auto widget = new QFrame;
widget->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
int id=widget->grabShortcut(QKeySequence::Delete, Qt::ShortcutContext::WidgetShortcut);
QObject::connect(widget, &QFrame::customContextMenuRequested, [widget,id](const QPoint& pos) {
QMenu menu(widget);
menu.setShortcutEnabled(id, true);
auto action = new QAction("&Copy node", &menu);
action->setShortcut(QKeySequence(QKeySequence::Delete));
action->setShortcutVisibleInContextMenu(true);
action->setShortcutContext(Qt::ShortcutContext::WidgetShortcut);
QObject::connect(action, &QAction::triggered, []() {
qDebug() << "Copy node triggered!";
});
menu.addAction(action);
menu.exec(widget->mapToGlobal(pos));
});
widget->show();
return a.exec();
}