菜单打开时键盘快捷键不会触发菜单中的 C++ Qt 操作
C++ Qt Action in menu not triggered by keyboard shortcut when menu open
我正在 Linux 上构建 Qt 应用程序。我在主 window 中有一个菜单栏,里面有两个菜单,每个菜单都有几个操作,所有这些都有与之关联的键盘快捷键。键盘快捷键在菜单未打开时有效,但当其中一个菜单打开时,其中 none 个有效。
在使用 [menuobject]->addAction 将操作添加到各自的菜单之前,使用 setShortcut 将快捷方式添加到操作中。所有的动作都有主要的 window 作为它们的 parent。阅读 QAction shortcut doesnt always work 后,我添加了对 addAction 的调用,将操作添加到主 window。这并没有解决问题。
菜单项之一的代码示例:
//In the main window constructor
gameQuit = new QAction(QString(tr("&Quit\tCtrl+Q")), this);
gameQuit->setShortcut(QKeySequence(Qt::Key_Q | Qt::CTRL));
addAction(gameQuit);
connect(gameQuit, SIGNAL(triggered()), this, SLOT(close()));
gameMenu = menuBar()->addMenu(QString(tr("&Game")));
gameMenu->addAction(gameQuit);
在我认为是用 Qt 编写的 QtCreator 中,菜单项的键盘快捷键在菜单打开时起作用,所以我认为一定有办法。
感谢您的帮助。
从引用的 post 的评论中吸取了一些建议(已被斥责,这就是我最初没有尝试的原因),我使用 [actionobject]->setShortcutContext( ).显然默认值在我的场景中不起作用。
我首先尝试设置为 Qt::WindowShortcut,但没有用。 Qt::ApplicationShortcut 确实有效,但是,正如所引用的 post 的评论中指出的那样,这可能存在缺点。不过,它们对我的这个特定应用程序并不重要,所以我要 post 并接受这个作为答案。
更正代码示例:
//In the constructor of the main window, after creation of the action and
//setting of the shortcut
gameQuit->setShortcutContext(Qt::ApplicationShortcut);
我正在 Linux 上构建 Qt 应用程序。我在主 window 中有一个菜单栏,里面有两个菜单,每个菜单都有几个操作,所有这些都有与之关联的键盘快捷键。键盘快捷键在菜单未打开时有效,但当其中一个菜单打开时,其中 none 个有效。
在使用 [menuobject]->addAction 将操作添加到各自的菜单之前,使用 setShortcut 将快捷方式添加到操作中。所有的动作都有主要的 window 作为它们的 parent。阅读 QAction shortcut doesnt always work 后,我添加了对 addAction 的调用,将操作添加到主 window。这并没有解决问题。
菜单项之一的代码示例:
//In the main window constructor
gameQuit = new QAction(QString(tr("&Quit\tCtrl+Q")), this);
gameQuit->setShortcut(QKeySequence(Qt::Key_Q | Qt::CTRL));
addAction(gameQuit);
connect(gameQuit, SIGNAL(triggered()), this, SLOT(close()));
gameMenu = menuBar()->addMenu(QString(tr("&Game")));
gameMenu->addAction(gameQuit);
在我认为是用 Qt 编写的 QtCreator 中,菜单项的键盘快捷键在菜单打开时起作用,所以我认为一定有办法。
感谢您的帮助。
从引用的 post 的评论中吸取了一些建议(已被斥责,这就是我最初没有尝试的原因),我使用 [actionobject]->setShortcutContext( ).显然默认值在我的场景中不起作用。
我首先尝试设置为 Qt::WindowShortcut,但没有用。 Qt::ApplicationShortcut 确实有效,但是,正如所引用的 post 的评论中指出的那样,这可能存在缺点。不过,它们对我的这个特定应用程序并不重要,所以我要 post 并接受这个作为答案。
更正代码示例:
//In the constructor of the main window, after creation of the action and
//setting of the shortcut
gameQuit->setShortcutContext(Qt::ApplicationShortcut);