Search code examples
c++qtsignals-slotsqt-signals

When to use signals and slots and when not to


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):

  • Is it ok to use signals to report errors?
  • Is it ok to assume that a signal will be handled?
  • Can signals be used to initiate actions? E.g. 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!


Solution

  • 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.