We're using Qt that offers signals and slots which I find really convenient. However, with great power comes great responsibility and I think it's very easy too misuse this feature.
Are there any best-practices for signal-slot usage? I'm having a hard time to find some general guidelines in this manner. Some questions (I have clear opinions about, but that not all members of my team agree with):
signal displayInfoScreen()
must be handled by a slot that shows an info screen.Any other opinions on when signals should/shouldn't be used are very welcome!
In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal.
It is generally unsafe to provide slots in your QThread subclass, unless you protect the member variables with a mutex. On the other hand, you can safely emit signals from your QThread::run() implementation, because signal emission is thread-safe.
if several slots are connected to one signal, the slots will be executed one after the other, in the order they have been connected, when the signal is emitted.
Signals and slots are powerful because decouples objects. You can't assume that a signal has a slot connected, as previously answered.
A major drawback of signal/slot based design is that you can very easy loose track of the logic you implemented, since one action of an object can trigger other actions of any other object that connected to a signal emitted. It is much easier to have unwanted side effects, recursive calls, etc.
Is it ok to use signals to report
errors?
Yes, for instance, see QFtp, where the done signal carries a status. It does not carry the actual error, just information that an error has occured.
Is it ok to assume that a signal will be handled?
No. The sender can never assume that, however, your particular application can depend on it. For instance, the QAction representing File - New needs to be handled for the application to work, but the QAction object couldn't care less.
Can signals be used to initiate actions? E.g. signal displayInfoScreen() must be handled by a slot that shows an info screen.
Again, yes, for instance the QAction object. But if you want to be able to reuse components, you must be careful to ensure that the actual class does not depend on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With