连接 lambda 时如何将 Qt::ConnectionType 传递给 QObject::connect?

How to pass Qt::ConnectionType to QObject::connect when connecting a lambda?

我正在将 lambda 连接到 QObject 的信号:

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

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

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

我将此添加到我的代码中:

    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 时获得排队连接?

我认为您需要使用 QObject::connect overload 来指定调用 lambda 的上下文...

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

如果没有目标对象上下文,排队的连接将无法工作,因为正是这个上下文选择了插槽调用插入到的队列。 To be more obtusely,包装仿函数的 QMetaCallEvent 被发布到上下文对象 thread() 的事件队列。