Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create QAction with shortcut, without inserting in menu

Tags:

c++

bind

qt

qaction

#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?

like image 385
Ashot Avatar asked Jan 31 '14 16:01

Ashot


1 Answers

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.

like image 152
Kuba hasn't forgotten Monica Avatar answered Sep 30 '22 13:09

Kuba hasn't forgotten Monica