Should I use Qt signal / slot mechanisms compared to traditional callbacks?

The senior developer on my team used traditional C-style callbacks in our Qt application instead of using the Qt signal / slot mechanisms.

My first reflex was to replace his code and use the Qt signal / slot.

Are there any good reasons to use callbacks in a Qt application / library?

Thanks.

+7
c ++ callback qt
source share
2 answers

I think the best approach would be to cover the structure you are using and use signal / slots.

Saying that if this code works and is not ugly or not causing problems, then you might be better off leaving it alone.

Consultation The signal / slot documentation describes why it is better to use the Signal / Slot approach:

Callbacks have two main drawbacks: First, they are not type specific. We can never be the processing function will call the callback with the correct arguments. Secondly, the callback is tightly coupled with the processing function because the processing function needs to know which callback to call.

Remember the following:

Compared to callbacks, signals and slots are slightly slower due to the greater flexibility they provide.

In most cases, speed probably doesn't matter, but there may be some extreme cases of recall that matter.

+18
source share

You must distinguish between callbacks that are synchronous and used to return both phased results and tuples (a few elements, such as a pair <> but more) and callbacks that are asynchronous free communication. Signals / slots should usually be used for the latter. For the former, it may make sense anyway, depending on whether it is the main function of your application (use signals / slots) or a library interface other than the GUI, which can be more portable (use direct callbacks for simple C / C ++ portable code).

As a rule, I have brief programming rules that tend to indicate what is the cleanest and least complex code / interface. For the case of a tuple return, I often use QMap rather than creating another class definition or signal / slot or callback method. This works well for picking and passing parameters, especially for things that need to be developed in different parts of the system.

+2
source share

All Articles