c++qtqt-signals

Is it allowed to emit a signal trough a pointer to an instance of another class?


Minimal example:

class Foo : public QObject
{
    Q_OBJECT

signals:

    void
    TestSignal(int i) const;
};

class Bar : public QObject
{
    Q_OBJECT

public:

     Bar(Foo* foo) :
         mFoo{ foo }
     {}

    void
    TestEmit(int i) const
    {
        emit mFoo->TestSignal(i);
    }

private:

    Foo* mFoo;
};

void
Print(int i)
{
    std::cout << i << std::endl;
}

Usage:

Foo aFoo;
Bar aBar{ &aFoo };

connect(&aFoo, &Foo::TestSignal, &Print);

aBar.TestEmit(1337);

So I'm emitting the signal Foo::TestSignal from function Bar::TestEmit using a pointer to a Foo instance. This seems to work fine, but is it allowed ? (as in: reliable defined behavior).


Solution

  • From https://doc.qt.io/qt-5/signalsandslots.html :

    Signals are public access functions and can be emitted from anywhere, but we recommend to only emit them from the class that defines the signal and its subclasses

    I understand it is technically allowed and reliable but not recommended in terms of code design.

    You might also be interested to connect a signal to another as explained here https://doc.qt.io/qt-5/qobject.html#connect