Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 755
Onur Tuna Avatar asked Mar 18 '17 15:03

Onur Tuna


2 Answers

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):

Snapshot of testQShortCut.exe (after pressing 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.

like image 101
Scheff's Cat Avatar answered Oct 29 '22 10:10

Scheff's Cat


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

like image 31
Patel Kalpesh Avatar answered Oct 29 '22 08:10

Patel Kalpesh