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.

4

2 回答 2

3

Functor不是真正的类型。它是 Qt 文档的占位符。真实类型是模板类型参数。检查QObject.h你是否真的感兴趣。在实践中,您可以使用std::function中定义的<functional>,来代替它。

对于问题中的函数,最简单的改变是使其成为模板函数:

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;
}
于 2013-03-16T16:05:47.613 回答
-2

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

函子只是一个void *或一个空指针。它可能需要是静态的。这似乎类似于常规的回调函数。

这是文档中的一个示例:

void someFunction();
QPushButton *button = new QPushButton;
QObject::connect(button, &QPushButton::clicked, someFunction);
于 2013-03-16T16:06:24.337 回答