7
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <cassert>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QAction* back = new QAction(this);
    back->setVisible(true);
    back->setShortcut(QKeySequence("Ctrl+M"));
    bool cres = connect(back, SIGNAL(triggered(bool)), this, SLOT(mySlot()));
    assert(cres);
}

In this code I tried to catch Ctrl+M key event. I don't want to put the action in menu. connect returns true but mySlot is never called. When action is inserted in menu, shortcut works well. What I have done wrong?

Ashot
  • 10,807
  • 14
  • 66
  • 117
  • 2
    If you want to use "headless" (without GUI) shortcuts, I would recommend using `QShortcut` class directly. – vahancho Jan 31 '14 at 17:02
  • @vahancho: `QShortcut` doesn't do anything without the gui. Quoth documentation: "A shortcut is "listened for" by Qt's event loop when the shortcut's parent widget is receiving events." – Kuba hasn't forgotten Monica Jan 31 '14 at 20:01
  • @KubaOber, yes, but what I meant was that QShortcut doesn't have a visual representation, as QAction may have. – vahancho Jan 31 '14 at 20:09

1 Answers1

7

QAction is dormant until you insert it somewhere. As vahancho has suggested, use QShortcut. You need to instantiate the shortcut for each top-level widget (window) where you want it to be active. Thus if you have 5 top-level windows, you'll need 5 shortcuts, each having one of windows as its parent.

There is no way to use QShortcut as a global shortcut without the gui. QShortcut is only active when its associated widget has focus. The widget could be a top-level window.

System-global shortcuts are the subject of this question.

Community
  • 1
  • 1
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313