Reputation: 4772
I want a QAction to be triggered by multiple keyboard shortcuts. According to the documentation, this should be possible by passing a list of QKeySequences to QAction::setShortcuts() , but in practice it seems that only the first key sequence in the list is used.
I've created a short example that demonstrates the problem. Here I'm trying to have both Meta+K and Ctrl+X (which are Alt+K and Cmd+X on the Mac) trigger "My Action". In this form, only Meta+K will trigger the action. If the two shortcuts are swapped so that Ctrl+X is first, then it will trigger the action and Meta+K will not. Finally, if all of the shortcut list stuff is commented out and the line with QKeySequence::Cut is uncommented, only Ctrl+X will work even though the documentation says that it maps to both Meta+K and Ctrl+X on the Mac. The code:
#include "mainwindow.h"
#include <QMenuBar>
#include <QAction>
MainWindow::MainWindow() {
QMenu* menu = new QMenu("Menu");
menuBar()->addMenu(menu);
QAction* action = new QAction("My Action", this);
// Create a list with two shortcuts
QList<QKeySequence> shortcuts;
shortcuts.append(QKeySequence(Qt::META + Qt::Key_K));
shortcuts.append(QKeySequence(Qt::CTRL + Qt::Key_X));
action->setShortcuts(shortcuts);
// Alternatively, use one of the QKeySequence::StandardKey enums
//action->setShortcuts(QKeySequence::Cut);
connect(action, SIGNAL(triggered()), this, SLOT(doIt()));
menu->addAction(action);
}
// slot
void MainWindow::doIt() { qDebug("MainWindow::doIt()"); }
If it matters, I'm using Mac OS X 10.9.2, and I've tried this with Qt 5.2.1 and Qt 5.3.0.
I'm including the header file and main.cpp in case anyone wants to just copy-and-paste to run the example, but there is nothing interesting or non-standard in them. Header file:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
public slots:
void doIt();
};
#endif // MAINWINDOW_H
main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
Upvotes: 2
Views: 1769
Reputation: 20163
Multiple keyboard shortcuts for a menu item are not supported on OS X. The QAction documentation notes "The result of calling this function will depend on the currently running platform".
It looks like the underlying cause is that OS X keeps the menu -> key shortcut mappings in a dictionary with the menu text as the key and the value as a single key atom (not any sort of collection), so there can be only one active key shortcut per menu item at a time.
Here a user found that even manually adding multiple keyboard shortcuts for the same menu item in a native application did not work - only the first was used.
Upvotes: 2