[Interest] Using connect/disconnect with lambdas

Thiago Macieira thiago.macieira at intel.com
Mon Feb 19 06:55:46 CET 2018


On Sunday, 18 February 2018 20:59:50 PST Tom Isaacson via Interest wrote:
> I'm replacing some old SIGNAL/SLOT connects with the new Qt5 format and I
> need to use lambdas for some of them.
> 
> Scenario 1:
> 
> public slots:
>     void RouteEditName();
>     void RouteEditName(QString name);
> 
>     m_pRouteEditNameAct = new tAction(tr("Name route") + "...", this);
>     connect(m_pRouteEditNameAct, SIGNAL(triggered()), this,
> SLOT(RouteEditName()), Qt::QueuedConnection);
> 
> If someone has been naughty and overloaded a slot then normally I'd just use
> a lambda to indicate which slot is being called:
> connect(m_pRouteEditNameAct, this, &tAction::triggered, [this]() {
> RouteEditName(); });

Make this a four-argument connect.

> But in this case I need to add Qt::QueuedConnection but connect() won't take
> four params like this: connect(m_pRouteEditNameAct, this,
> &tAction::triggered, [this]() { RouteEditName(); }, Qt::QueuedConnection);

Make this one a five-argument connect().

> Do I just add an unnecessary 'this' to fill it out?
>     connect(m_pRouteEditNameAct, this, &tAction::triggered, this, [this]() {
> RouteEditName(); }, Qt::QueuedConnection);

It's not unnecessary. It's good practice.

And in your case, absolutely necessary. You cannot queue a connection without 
a target QObject to be queued to. THAT is what that extra "this" is for.

> Scenario 2:
> 
> Later I need to disconnect this:
>     disconnect(m_pRouteEditNameAct, SIGNAL(triggered()), this,
> SLOT(RouteEditName()));
> 
> But how do I disconnect a lambda?
>     disconnect(m_pRouteEditNameAct, &tAction::triggered, this, [this]() {
> RouteEditName(); });

disconnect() does not have such an overload. To disconnect anew-style connect, 
you must pass the QMetaObject::Connection object that connect() returned.

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center






More information about the Interest mailing list