QObject::connect 的函数包装器

A function wrapper around QObject::connect

我正在尝试编写一个将其参数传递给 QObject::connect 的函数。

template <typename Func1, typename Func2>
void addConnection(const QObject* sender, Func1 signal, Func2 slot)
{
    m_connections.push_back(QObject::connect(sender, signal, slot));
}

我是这样称呼它的:

addConnection(&m_scannerSystem, &ScannerSystem::signalStatus, [=](int status){ this->onStatusChanged(status); });

这会导致错误:

'QObject::connect' : none of the 4 overloads could convert all the argument types

但我无法弄清楚为什么它不起作用。

您是否阅读了编译器错误消息?编译器在 5 个重载函数中不知道合适的 QObject::connect() 函数。 QT doc

如果使用下面的代码,编译会成功。

addConnection( &m_scannerSystem, SIGNAL( signalStatus( int ) ), this, SLOT( onStatusChanged( int ) ) );

你的问题是你试图传递一个指向 QObject 的指针,但是在那种情况下你如何能够调用另一个对象(在你的例子中是 ScannerSysterm)的成员函数?系统必须知道传递的发件人的实际类型。所以你可以这样修复它:

template <typename Sender, typename Func1, typename Func2>
void addConnection(const Sender* sender, Func1 signal, Func2 slot)
{
    QObject::connect(sender, signal, slot);
}

或者通过使用一些神奇的 Qt 特性:

template <typename Func1, typename Func2>
void addConnection(const typename QtPrivate::FunctionPointer<Func1>::Object* sender, Func1 signal, Func2 slot)
{
    QObject::connect(sender, signal, slot);
}