Search code examples
qtsignals-slots

How to connect signals and slots with transformed argument values


Any easy way to connect signals and slots with transformed argument values. For example, I have a single signal(bool state), it is connected to a slot slot(bool reversed_state) here the state is a reversed state (logically not) of the signal state.


Solution

  • Create an intermediate slot to link the two: -

    class MyClass : public QObject
    {
        Q_OBJECT
    public:
        signals:
            void SomeSignal(bool state);
            void SomeSignalSwitched(bool state); // reverse the state
    
        public slots:            
    
            void ReversedStateSlot(bool reversed_state);
     };
    
    
    void MyClass::SomeSignalSwitched(bool state)
    {
        bool newState = !state
        emit SomeSignalSwitched(newState);
    }
    
    // NOTE Qt 5 connect functions
    
    connect(myClassObject, &MyClass::SomeSignal, myClassObject, &MyClass::SomeSignalSwitched);
    connect(myClassObject, &MyClass::SomeSignalSwitched, myClassObject, &MyClass::ReversedStateSlot);