Search code examples
c++qtshortcut

How do I add a custom ApplicationShortcut in Qt


I have the following code:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    mUi(new Ui::MainWindow)
{
    mUi->setupUi(this);
    this->setFixedSize(this->width(), this->height());

    StyleUi();

    auto closeAct = new QAction(this);
    closeAct->setShortcut(QKeySequence("Ctrl+O"));
    connect(closeAct, SIGNAL(activated()), this, SLOT(close()));
    closeAct->setShortcutContext(Qt::ApplicationShortcut);
    addAction(closeAct);
}

The last 5 lines define a QAction with a shortcut created from the sequence Ctrl+O, connects the QAction the the slot Close(). I've found this example here on stackoverflow and several other documentation sites describe what I want to do as such. However, I am not getting anywhere with this. My program doesn't close when I hit Ctrl+O. Any suggestions on where I am doing something wrong?


Solution

  • You can create it by using the multiple arguments constructor for QKeySequence.

    like this:

    QShortcut *shortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_O), this);
    shortcut->setContext(Qt::ApplicationShortcut);
    

    And try this to get QShortcut signal activated:

    connect(shortcut, &QShortcut::activated, this, &MainApp::activeShortcut);
    
    void MainApp::activeShortcut()
    {
        this->close();
    }
    

    This is a sample project for your question on github download here.