jaho
jaho

Reputation: 5002

A function wrapper around QObject::connect

I'm trying to write a function which passes its arguments to 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));
}

and here is how I'm calling it:

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

This results in an error:

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

but I'm not able to figure out why it doesn't work.

Upvotes: 4

Views: 915

Answers (2)

ixSci
ixSci

Reputation: 13698

You problem is that you are trying to pass a pointer to QObject but how in that case you would be able to call a member function of the other object(ScannerSysterm in your case)? The system has to know the actual type of the passed sender. So you might fix it this way:

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

Or by using some magic Qt traits:

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

Upvotes: 4

hyun
hyun

Reputation: 2143

Have you read the compiler error message? The compiler doesn't know a suitable QObject::connect() function among 5 overload functions. QT doc

If you use below code, compile will success.

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

Upvotes: 0

Related Questions