How do I add a custom ApplicationShortcut in Qt

*爱你&永不变心* 提交于 2019-12-11 08:52:17

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/46072018/how-do-i-add-a-custom-applicationshortcut-in-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!