Why the QAction only added to menu can let the shortcut work?
such as the code I write:
QAction *m_ACEsc = new QAction(QString("exit"),this); m_ACEsc->setShortcut(QString("esc")); QObject::connect(m_ACEsc,SIGNAL(triggered()),qApp,SLOT(quit()));
when I press the ESC keyboard, there's no triggered signal emitted.
only after add to menu :
The shortcut working.
Why? But I don't want the action show in the menu. And I know I can overwrite keyPressEvent to do same thing, but I just want to use QAction do the job. What should I do?
Thanks in advance!
QAction is intended as a visual element. If you just want a shortcut that you can bind to use QShortcut instead.
@Chris-Kawa Thanks very much. You get the point and answer very fast !
Btw. avoid strings when not necessary. Instead of
QString("esc")you can use
Qt::Key_Escapeand there's also a connect syntax in Qt5 that does not use strings (via macros):
QShortcut* sh = new QShortcut(Qt::Key_Escape, this); connect(sh, &QShortcut::activated, qApp, &QApplication::quit);
@Chris-Kawa yeah, you are right. But I use the QString in order to let users to redefine their shortcut, so I didn't use the constant.
Whenever you let user enter strings you need to validate them. You can use a specialized widget for that: QKeySequenceEdit. It allows you to input a key sequence and stores it in a QKeySequence that you can pass around.