Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading