How to Program custom Keyboard Shortcuts

爷,独闯天下 提交于 2019-11-30 01:43:57
dtech

Try this:

new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close()));

You can create it in the contructor of your form. This allows to avoid polluting your class with a pointer to access the shortcut. You may still want to add a pointer to the shortcut if you want to access it later on. The shortcut will be deleted when the application exits, since it is parented to it. It automatically does the connection, you don't have to do it manually.

Also note that there is no default Ctrl+Q sequence on Windows, but there is one on Linux and MacOS.

Since CTRL-Q may have a menu item or toolbar entry, too, I think you're looking for QAction.

See this: http://doc.qt.digia.com/4.6/qaction.html#shortcut-prop

LE:

Example of QAction at work:

QAction *foo = new QAction(this);
foo->setShortcut(Qt::Key_Q | Qt::CTRL);

connect(foo, SIGNAL(triggered()), this, SLOT(close()));
this->addAction(foo);

Just create a new Qt GUI project (I used QtCreator) and add that code to the main window's constructor and it should work as expected.

Please note that there is no need of freeing the memory since the Qt framework will take care of that when the app closes.

For the modern Qt (5.9 as of now):

void MainWindow::bootStrap()
{
    // create shortcut
    QShortcut *shortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this);

    // connect its 'activated' signal to your function 'foo'
    QObject::connect(shortcut,    &QShortcut::activated,
                     this,        &MainWindow::foo);
}

// somewhere in the code, define the function 'foo'
void MainWindow::foo()
{
    qDebug() << "Ctrl+Q pressed.";
}

Don't forget to #include <QShortcut>.

Further info: http://doc.qt.io/qt-5/qshortcut.html

this is a sample to create file menu and exit action and connection between signal and slot.

QMenu *fileMenu = new QMenu(trUtf8("&File"));
QAction *actionExit = new QAction(tr("E&xit"));    
//set "ctrl+q shortcut for exit action
actionExit->setShortcut(tr("CTRL+Q"));
//connect triggered signal of actionExit to close slot
connect(actionExit, SIGNAL(triggered()), this, SLOT(close()));
//add actionExit into file menu
fileMenu->addAction(actionExit);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!