Search code examples
c++qtlambdasignals-slots

Lambda expression when shortcut triggered (Qt)


In Qt, I'm trying to add some shortcuts to my GUI. I can do it simply by deffining each of the shortcuts like this and then like them to their respective function:

QObject::connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_B), this), SIGNAL(activated()), this, SLOT(myFunc()));

The line from above works as expected. I'd like, however, to avoid creating different functions for each of the shortcuts. That's why I'd like to use lambda expressions. I'm tring to make this bit of code work:

QShortcut *shortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_B), this);
QObject::connect(shortcut, SIGNAL(activated()), [=]() 
{
    myFunc();
});

However, the connect from above is not allowed. How can I solve this?


Solution

  • Maybe you should use new style syntax like:

    QObject::connect(shortcut, &QShortcut::activated, [=]() 
    {
        myFunc();
    });
    

    Reference