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

99封情书 提交于 2020-01-24 03:51:06

问题


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?


回答1:


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

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.




回答2:


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



来源:https://stackoverflow.com/questions/42876347/how-to-set-3-key-sequence-shortcut-with-two-key-modifiers-in-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!