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?
Maybe you should use new style syntax like:
QObject::connect(shortcut, &QShortcut::activated, [=]()
{
myFunc();
});
Reference
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With