使用快捷方式创建QAction,无需插入菜单

Ash*_*hot 4 c++ qt bind 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);
}
Run Code Online (Sandbox Code Playgroud)

在这段代码中,我尝试捕获Ctrl+M关键事件。我不想将操作放在菜单中。connect返回true,但从mySlot不调用。在菜单中插入动作后,快捷方式可以正常工作。我做错了什么?

Rei*_*ica 5

QAction在将其插入某个位置之前处于休眠状态。如vahancho所建议,使用QShortcut。您需要实例化每个希望其处于活动状态的顶级窗口小部件(窗口)的快捷方式。因此,如果您有5个顶级窗口,则需要5个快捷方式,每个快捷方式都将其中一个窗口作为其父窗口。

没有QShortcutgui,无法用作全局快捷方式。QShortcut仅在其关联的小部件具有焦点时才处于活动状态。该小部件可以是顶级窗口。

系统全局快捷方式是这个问题的主题。