I'm trying to write a function which passes its arguments to 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));
}
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.
但我无法弄清楚它为什么不起作用。
2 个解决方案
#1
3
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:
您的问题是您正在尝试将指针传递给QObject但是在这种情况下您将如何调用另一个对象的成员函数(在您的情况下为ScannerSysterm)?系统必须知道传递的发件人的实际类型。所以你可以用这种方式解决它:
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:
或者通过使用一些神奇的Qt特征:
template <typename Func1, typename Func2>
void addConnection(const typename QtPrivate::FunctionPointer<Func1>::Object* sender, Func1 signal, Func2 slot)
{
QObject::connect(sender, signal, slot);
}
#2
0
Have you read the compiler error message? The compiler doesn't know a suitable QObject::connect()
function among 5 overload functions. QT doc
您是否阅读过编译器错误消息?编译器在5个重载函数中不知道合适的QObject :: connect()函数。 QT doc
If you use below code, compile will success.
如果您使用下面的代码,编译将成功。
addConnection( &m_scannerSystem, SIGNAL( signalStatus( int ) ), this, SLOT( onStatusChanged( int ) ) );
#1
3
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:
您的问题是您正在尝试将指针传递给QObject但是在这种情况下您将如何调用另一个对象的成员函数(在您的情况下为ScannerSysterm)?系统必须知道传递的发件人的实际类型。所以你可以用这种方式解决它:
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:
或者通过使用一些神奇的Qt特征:
template <typename Func1, typename Func2>
void addConnection(const typename QtPrivate::FunctionPointer<Func1>::Object* sender, Func1 signal, Func2 slot)
{
QObject::connect(sender, signal, slot);
}
#2
0
Have you read the compiler error message? The compiler doesn't know a suitable QObject::connect()
function among 5 overload functions. QT doc
您是否阅读过编译器错误消息?编译器在5个重载函数中不知道合适的QObject :: connect()函数。 QT doc
If you use below code, compile will success.
如果您使用下面的代码,编译将成功。
addConnection( &m_scannerSystem, SIGNAL( signalStatus( int ) ), this, SLOT( onStatusChanged( int ) ) );