Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 895
karl71 Avatar asked Jul 19 '26 03:07

karl71


2 Answers

Maybe you should use new style syntax like:

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

Reference

like image 197
Max Pashkov Avatar answered Jul 21 '26 19:07

Max Pashkov


This is how I do it with C++11 lambda syntax:

QObject::connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q),  this), &QShortcut::activated, [=](){    this->close();  });

And this is how I do it with a (previously declared) slot:

QObject::connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_T),  this), &QShortcut::activated, this, &ClassName::fancySlot);
like image 42
Antornix Avatar answered Jul 21 '26 19:07

Antornix