How to create a single-shot, one-time connection to a lambda?
-
I use the new Qt5 syntax and lambdas a lot, e. g.:
connect(_textFadeOutAnimation, &QPropertyAnimation::finished, [this, text](){ });
The problem I'm facing right now is I need this slot to only be fired once. Since there's no
ConnectionType
for that, I need todisconnect
inside the slot, apparently. But how do I disconnect a lambda? I can't pass theQMetaObject::Connection
inside the lambda for the obvious reason... -
Hi @Violet-Giraffe,
Interesting question.
What about something like (untested):
QMetaObject::Connection * const connection = new QMetaObject::Connection; *connection = connect(_textFadeOutAnimation, &QPropertyAnimation::finished, [this, text, connection](){ QObject::disconnect(*connection); delete connection; });
-
@Paul-Colby, brilliant, that works! Thank you. It didn't occur to me
Connection
has an assignment operator. -
This post is deleted!
-
There is another way. Create a context object and use it as receiver for the connection. If you delete it, the connected signal will be disconnected.
QObject* ctx = new QObject(); connect(d, &MyClass::mySignal, ctx, [=]() { // destroy the context/receiver to disconnect ctx->deleteLater(); // slot routine here... });
-
@Violet-Giraffe Mark the thread as 'solved', please.
-
In Qt6 there is a new connection type Qt::SingleShotConnection.
See more in this KDAB blog: https://www.kdab.com/single-shot-connections/