JB_User
JB_User

Reputation: 3267

How to Program custom Keyboard Shortcuts

I have a Qt application on Linux.

I'd like to program custom keyboard shortcuts such as CTRL-Q which will then call a subroutine which quits the program.

How can I do this?

Upvotes: 32

Views: 40307

Answers (4)

Neurotransmitter
Neurotransmitter

Reputation: 6827

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

Upvotes: 13

saheb khanari amrei
saheb khanari amrei

Reputation: 29

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);

Upvotes: 2

dtech
dtech

Reputation: 49329

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.

Upvotes: 48

Paul
Paul

Reputation: 22005

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.

Upvotes: 34

Related Questions