Search code examples
c++qtc++11lambdaslot

A slot as a paramater in a lambda function in C++ / Qt


I have a lambda method which I would like to receive a slot as a parameter

I have ended up with:

  auto createShortcuts = [ = ]( const QString &sequence, const std::function < void () > &slot  )
  {
    QShortcut *sc = new QShortcut( QKeySequence( sequence ), this );
    connect( sc, &QShortcut::activated, mMyObject, slot );
  };

  createShortcuts( QStringLiteral( "whatever" ), [=](){mMyObject->mySlot();} );

But I would prefer avoid using a lambda slot when calling createShortcuts. Rather something like

  auto createShortcuts = [ = ]( const QString &sequence, void ( MyObject::* )() )
  {
    QShortcut *sc = new QShortcut( QKeySequence( sequence ), this );
    connect( sc, &QShortcut::activated, mMyObject, ??? );
  };

  createShortcuts( QStringLiteral( "whatever" ), &MyObject::mySlot );

But I couldn't find the proper syntax to call the slot.


Solution

  • This should work, you're just missing the name of the function pointer.

      auto createShortcuts = [ = ]( const QString &sequence, void ( MyObject::* myFunc )() )
      {
        QShortcut *sc = new QShortcut( QKeySequence( sequence ), this );
        connect( sc, &QShortcut::activated, mMyObject, myFunc);
      };
    
      createShortcuts( QStringLiteral( "whatever" ), &MyObject::mySlot );
    

    Edit: The above solution works only if the mMyObject is declared in the same scope createShortcuts is declared, the below is safer.

      auto createShortcuts = [ = ]( const QString &sequence, const MyObject* mMyObject, void ( MyObject::* myFunc )() )
      {
        QShortcut *sc = new QShortcut( QKeySequence( sequence ), this );
        connect( sc, &QShortcut::activated, mMyObject, myFunc);
      };
      auto obj = new MyObject();
      createShortcuts( QStringLiteral( "whatever" ), obj, &MyObject::mySlot );