[Interest] Using connect/disconnect with lambdas
Benjamin TERRIER
b.terrier at gmail.com
Mon Feb 19 13:48:52 CET 2018
2018-02-19 5:59 GMT+01:00 Tom Isaacson via Interest <interest at qt-project.org>:
> 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(); });
>
> 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);
>
> Do I just add an unnecessary 'this' to fill it out?
> connect(m_pRouteEditNameAct, this, &tAction::triggered, this, [this]() { RouteEditName(); }, Qt::QueuedConnection);
>
There is a big difference between :
connect(ptr, SIGNAL(triggered()), ptr2, SLOT(mySlot()));
and
connect(ptr, &Ptr::triggered, ptr2, [ptr2]() { ptr2->mySlot(); });
and
connect(ptr, &Ptr::triggered, [ptr2]() { ptr2->mySlot(); });
The first 2 forms behave identically and the slot (and lambda) is
executed in the thread
of the ptr2 object.
While the 3rd form executes the lambda and the slot in the thread of ptr object.
So if you want to solve overloads by using lambdas you should use the 2nd form.
Alternatively, you can use QOverload and qOverload to resolve the
overload without having to pay for a lambda.
Br,
Benjamin
More information about the Interest
mailing list