reducing signal/slot indirection
-
Hi all -
Early in my (still young) Qt education, I was advised that it was acceptable practice to use slots to relay the signal on to another object, perhaps in a different thread, that the signaler couldn't see.
I fear that I've taken this to an extreme in my current project. I have a worker thread as well as my main (UI) thread. Both my worker object and my main UI object have private objects that raise signals that need to be passed along to the other main object. So, I do a lot of signalling. Here's an example: if my user presses a cancel button on a file transfer dialog, the dialog must signal the main UI (who owns the file transfer dialog), who in turn informs the worker, who in turn signals the file transfer object. That's three pairs of signals/slots. These add up fast.
I realize that from a performance standpoint, this is fine, but coding clarity suffers. Is this just how it has to be in Qt land, or am I unaware of a more parsimonious alternative?
-
Hi,
Did you already use signal chaining ?
-
class MyCoolClass : public QObject { Q_OBJECT public: MyCoolClass(QObject *parent = nullptr) : QObject(parent) { connect(&timer, &QTimer::timeout, &MyCoolClass::timeout); } signals: void timeout(); private: QTimer timer; }
-
It's equivalent to:
connect(&timer, &QTimer::timeout, this, &MyCoolClass::timeout);
-
@mzimmers said in reducing signal/slot indirection:
Is this documented anywhere? I searched for the word "chain" in one of the signals and slots pages, and it came up empty.
It's not very clear, but the Signals & Slots page says, "You can connect as many signals as you want to a single slot, and a signal can be connected to as many slots as you need. It is even possible to connect a signal directly to another signal. (This will emit the second signal immediately whenever the first is emitted.)"
-
@mzimmers FYI, if you find yourself doing a lot of signal forwarding, you may want to consider using Observer pattern instead. In this case you forward observer object once to your "deepest" class which emits signals, and call observers virtual methods directly to "emit signal"