简体   繁体   中英

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

I have been trying to set a shortcut as Ctrl + Shift + C .

I have tried the following ways:

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 didn't work. Nothing is triggered when I press Ctrl + Shift + C .

Is it impossible to set a shortcut with two modifiers in Qt?

I wrote a minimal, complete sample. It worked in my case how you described it. May be, I added something which you didn't on your side. (That's why "minimal, complete, verifiable 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();
}

I suspect that you didn't call QWidget::addAction() . If I comment it out it does not work anymore in my program also.

Compiled with VS2013 and Qt 5.6 on Windows 10 (64 bit):

testQShortCut.exe快照(按Ctrl + Shift + Q后)

This snapshot has been made after pressing Ctrl+Shift+Q.

Note:

I realized afterwards that the actual question was about "Ctrl+Shift+C". To be sure, I checked it. The above sample code works with "Ctrl+Shift+C" as well.

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

just change above mention statement in your code to

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

this should work fine. "C" should be capital later.

please refer key sequence from below given link http://doc.qt.io/qt-5/qkeysequence.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM