4
votes

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.

2
Where is your Functor type declared?Tony The Lion
Qt declared the type Functor, as its document shows. but I cannot find where it is declared.user1899020

2 Answers

3
votes

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;
}
-2
votes

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);