4

Qt can use lambda function in signal-slot connection by using functor parameter as shown here. But how to declare functor parameter in Qt connect? For example,

QAction* CreateAction(QString text, QObject* parent, Functor functor)
{
    QAction* action = new QAction(icon, text, parent);
    QObject::connect(action, &QAction::triggered, functor);
    return action;
}

Question is how to include files to let the compiler know the "Functor" type.

Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
user1899020
  • 13,167
  • 21
  • 79
  • 154

2 Answers2

3

Functor is not a real type. It's a placeholder for Qt documentation. The real type is a template type parameter. Check QObject.h if you are really interested. In practice, you can use std::function, which is defined in <functional>, in its place.

For the function in the question, the simplest change is to make it a template function:

template<Functor>
QAction* CreateAction(QString text, QObject* parent, Functor&& functor)
{
    QAction* action = new QAction(icon, text, parent);
    QObject::connect(action, &QAction::triggered, std::forward<Functor>(functor));
    return action;
}
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Stephen Chu
  • 12,724
  • 1
  • 35
  • 46
  • @TobySpeight it was a snippet targeting Stephens answer, thus an example with `std::function`. Either way, there's code now ;-) – Bayou Jun 20 '19 at 14:25
-2

http://qt-project.org/doc/qt-5.0/qtcore/qobject.html#connect-5

A functor is just a void * or a void pointer. It might need to be static. This seems similar to a regular call back function.

Here is an example from the documentation:

void someFunction();
QPushButton *button = new QPushButton;
QObject::connect(button, &QPushButton::clicked, someFunction);
phyatt
  • 18,472
  • 5
  • 61
  • 80
  • 2
    It's not a void*. Read the header. http://qt.gitorious.org/qt/qtbase/blobs/stable/src/corelib/kernel/qobject.h#line243 – Stephen Chu Mar 16 '13 at 16:30