iammilind
iammilind

Reputation: 70100

Will a disconnect() called on a particular `QObject::Signal()` will disconnect lambda automatically?

Suppose, there is a lambda connected to a signal as below:

connect(pObject, &Object::mySignal, [] () { lambda; });

Will below statement disconnect the lambda automatically?

disconnect(pObject, &Object::mySignal, nullptr, nullptr);

I am asking this, because in the QObject::disconnect's documents there are 2 contradicting statements:

2 Disconnect everything connected to a specific signal:
disconnect(myObject, SIGNAL(mySignal()), nullptr, nullptr);

and

Note: It is not possible to use this overload to disconnect signals connected to functors or lambda expressions. That is because it is not possible to compare them. Instead, use the overload that takes a QMetaObject::Connection`

Related: Disconnecting lambda functions in Qt5

Upvotes: 2

Views: 175

Answers (1)

G.M.
G.M.

Reputation: 12909

Just to clarify, the two quotes you gave are in fact from different QObject::disconnect overloads.

In summary, the call...

disconnect(myObject, &MyObject::mySignal, nullptr, nullptr);

should disconnect everything connected to the MyObject::mySignal signal of the MyObject instance pointed to by myObject -- including lambdas/functors.

I think the perceived contradiction comes from the fact that the second statement (the "Note") is rather badly worded. What it should state is...

Note: It is not possible to use this overload to disconnect signals connected to specific functors or lambda expressions. ...

Hence, given the 'mocked up' code...

QPushButton *pb = ...
auto slot = [](bool checked) { /* Some useful stuff. */ };
connect(pb, &QPushButton::clicked, this, slot);

it is not then possible to do...

disconnect(pb, &QPushButton::clicked, this, slot);

If, however, you do as the quote says and...

...use the [disconnect] overload that takes a QMetaObject::Connection

then the following should work...

auto connection = connect(pb, &QPushButton::clicked, this, slot);
disconnect(connection);

[Note: I don't have Qt installed on the box, so the above is untested.]

Upvotes: 3

Related Questions