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?


  • Lifetime Qt Champion

    Hi,

    Did you already use signal chaining ?



  • Hi SGaist - I'm not finding much documentation on that term. Can you give me a short definition?


  • Lifetime Qt Champion

    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;
    }
    


  • A connect() call with only 3 arguments?


  • Lifetime Qt Champion

    It's equivalent to:

    connect(&timer, &QTimer::timeout, this, &MyCoolClass::timeout);



  • OK, so then what you're accomplishing is the elimination of a slot routine, yes? That would be a big help.

    Is this documented anywhere? I searched for the word "chain" in one of the signals and slots pages, and it came up empty.


  • Moderators

    @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"



  • Thanks, Konstantin. I'll keep that in mind for future projects.


 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.