1

I have many QActions and I would like to connect their triggered(bool) signal to a specific slot which gets an integere number as input, let's say setX(int x). I need to specify x in connect callback. For example:

connect(actionV, &QAction::triggered,
        this, &TheClass::setX /* somehow x=10 */);

I tried using std::bind and it does not work:

connect(actionV, &QAction::triggered,
        std::bind(this, &TheClass::setX, 10));
sorush-r
  • 9,347
  • 14
  • 77
  • 160
  • 4
    To begin with, you use [`std::bind`](http://en.cppreference.com/w/cpp/utility/functional/bind) wrong. The first argument is the "function" that should be called. – Some programmer dude Jul 13 '18 at 08:20
  • 1
    For this, I prefer lambdas and it's working fine (especially if receiver is not a `QObject`). e.g. `QObject::connect(actionV, &QAction::triggered, [&](bool) { setX(10); });` – Scheff's Cat Jul 13 '18 at 08:21
  • 1
    Related: https://stackoverflow.com/questions/17363003/why-use-stdbind-over-lambdas-in-c14/17545183 If you use C++14, you should avoid `std::bind` altogether. – Jaa-c Jul 13 '18 at 08:22
  • @Someprogrammerdude Oh... Yes it is wrong indeed (: Passing this as second argument, now works. Thank you – sorush-r Jul 13 '18 at 08:42

1 Answers1

3

You can solve this easily using a lambda:

connect(actionV, &QAction::triggered, [&] { 
   m_theClass.setX(10);
});
Mahmoud Badri
  • 1,078
  • 10
  • 23