2017-02-10 106 views
2

我连接的lambda到QObject的信号:如何在连接lambda时将Qt :: ConnectionType传递给QObject :: connect?

QObject::connect(handle, &BatchHandle::progressMax, [this](const ProcessHandle* const self, const int value) { 
     this->maxProgress(value); 
    }); 

上面的代码没有问题编译。

但是,因为handle对象最终会移动到另一个线程,所以Qt::QueuedConnection是绝对必要的。

我将此添加到我的代码:

QObject::connect(handle, &BatchHandle::finished, [this](const ProcessHandle* const self) { 
     this->processIsRunning(false); 
    }, (Qt::ConnectionType)Qt::QueuedConnection); 

注意我是如何加入明确的转换,以确保它正确标识值类型。结果:

1>src\TechAdminServices\database\techCore\processes\import\ImportManagerDialog.cpp(191): error C2664: 'QMetaObject::Connection QObject::connect<void(__cdecl taservices::ProcessHandle::*)(const taservices::ProcessHandle *),Qt::ConnectionType>(const taservices::ProcessHandle *,Func1,const QObject *,Func2,Qt::ConnectionType)' : cannot convert parameter 3 from 'taservices::`anonymous-namespace'::<lambda58>' to 'const QObject *' 
1>   with 
1>   [ 
1>    Func1=void (__cdecl taservices::ProcessHandle::*)(const taservices::ProcessHandle *), 
1>    Func2=Qt::ConnectionType 
1>   ] 
1>   No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 

如何在连接lambda时获得排队连接?

+0

我认为这将是一个骗局,因为对目标上下文的要求确实使它有点不直观,但显然不是。 –

回答

6

我认为你需要使用QObject::connect overload,使您可以指定在其中拉姆达被调用的背景下...

QObject::connect(
    handle, 
    &BatchHandle::progressMax, 
    target_context, /* Target context parameter. */ 
    [this](const ProcessHandle* const self, const int value) 
    { 
    this->maxProgress(value); 
    }, 
    Qt::QueuedConnection); 
0

排队的连接不能没有目标对象环境中工作,因为这是选择插槽调用插入的队列的上下文。包含函子的To be more obtuselyQMetaCallEvent被发布到上下文对象thread()的事件队列。