Disconnect/Connect using RAII paradigm
Solved
General and Desktop
-
Hello, I would like to use RAII paradigm for operations involving disconnect and then connect.
In the following, an example of what I have:disconnect(sender, signal, receiver, method); // Do something connect(sender, signal, receiver, method);
or even
disconnect(sender, signal, receiver, method); disconnect(sender2, signal2, receiver2, method2); // Do something connect(sender, signal, receiver, method); connect(sender2, signal2, receiver2, method2);
This is motivated by the fact that the code in the middle would otherwise send a signal, that I don't want to emit.
Is there any clean way to write the same using RAII paradigm? Something like:
TemporaryDisconnect(sender, signal, receiver, method, []{ doSomething(); });
I don't have much experience so I was trying with:
template <typename PointerToMemberFunction> class TemporaryDisconnect : public QObject { const QObject *sender, *receiver; PointerToMemberFunction signal, method; TemporaryDisconnect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, std::function<void()> f) { this->sender = sender; this->signal = signal; this->receiver = receiver; this->method = method; disconnect(sender, signal, receiver, method); f(); } ~TemporaryDisconnect() { connect(sender, signal, receiver, method); } };
The code above is just to give an idea of what is my goal. Do you have any suggestions?
-
Hi,
I think QSignalBlocker would be simpler.
-
That's the idea yes.
-
If you need that fine grained surgery then it might mean that your architecture may not be optimal.
Can you give a practical use case example ?