How to set a 3-key keyboard shortcut with two key modifiers in Qt?

I'm trying to set a shortcut as a Ctrl+ Shift+ C.

I tried the following methods:

QAction *generalControlAction = new QAction(this);
generalControlAction->setShortcut(QKeySequence("Ctrl+Shift+c"));
connect(generalControlAction, &QAction::triggered, this, &iBexWorkstation::onGeneralConfiguration);

QShortcut *generalControlShortcut = new QShortcut(QKeySequence("Ctrl+Shift+C"), this);
connect(generalControlShortcut, &QShortcut::activated, this, &iBexWorkstation::onGeneralConfiguration);

They did not work. Nothing works when I press Ctrl+ Shift+ C.

Can't set a shortcut with two modifiers in Qt?

+6
source share
2 answers

I wrote a minimal, complete sample. In my case, it worked as you described it. Maybe I added something that you did not do on your side. (This is why “minimal, complete, tested samples” are preferred.)

// standard C++ header:
#include <iostream>

// Qt header:
#include <QAction>
#include <QApplication>
#include <QLabel>
#include <QMainWindow>

using namespace std;

int main(int argc, char **argv)
{
  cout << QT_VERSION_STR << endl;
  // main application
#undef qApp // undef macro qApp out of the way
  QApplication qApp(argc, argv);
  // the short cut
  const char *shortCut = "Ctrl+Shift+Q";
  // setup GUI
  QMainWindow qWin;
  QAction qCmdCtrlShiftQ(&qWin);
  qCmdCtrlShiftQ.setShortcut(QKeySequence(shortCut));
  qWin.addAction(&qCmdCtrlShiftQ); // DON'T FORGET THIS.
  QLabel qLbl(
    QString::fromLatin1("Please, press ")
    + QString::fromLatin1(shortCut));
  qLbl.setAlignment(Qt::AlignCenter);
  qWin.setCentralWidget(&qLbl);
  qWin.show();
  // add signal handlers
  QObject::connect(&qCmdCtrlShiftQ, &QAction::triggered,
    [&qLbl, shortCut](bool) {
    qLbl.setText(
      QString::fromLatin1(shortCut)
      + QString::fromLatin1(" pressed."));
  });
  // run application
  return qApp.exec();
}

, QWidget::addAction(). , .

VS2013 Qt 5.6 Windows 10 (64 ):

Snapshot testQShortCut.exe (after pressing Ctrl + Shift + Q)

Ctrl + Shift + Q.

:

, "Ctrl + Shift + C". , . "Ctrl + Shift + C".

+4

generalControlAction- > setShortcut (QKeySequence (Ctrl + Shift + c));

generalControlAction- > setShortcut ((Ctrl + Shift + c));

. "C" .

, http://doc.qt.io/qt-5/qkeysequence.html

+2

Source: https://habr.com/ru/post/1015862/


All Articles