Create QAction with shortcut, without inserting in menu
Asked Answered
S

1

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?

Stearic answered 31/1, 2014 at 16:51 Comment(3)
If you want to use "headless" (without GUI) shortcuts, I would recommend using QShortcut class directly.Kanal
@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."Frugivorous
@KubaOber, yes, but what I meant was that QShortcut doesn't have a visual representation, as QAction may have.Kanal
H
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.

Hexarchy answered 31/1, 2014 at 18:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.