Search code examples
qtsignals-slotsqobject

Qt: Get notified when a signal is connected


Is it possible to get notified that a signal is being connected to some slot?

For example, we have class Foo:

class Foo : public QObject
{
    Q_OBJECT

...
signals:
    void fooChanged(int bar);
};

And somewhere, someone connects it:

Foo *foo = new Foo;
connect(foo, SIGNAL(fooChanged(int)),
        other, SLOT(setFoo(int)));

I would like to get my code invoked when connect() is called, so I can register Foo in a server to receive the network events that will cause the signal to be emitted. This way, I could just connect the signal and the sender would automagically register in the server to receive the required events, which would be much less error-prone than requiring manual registration. For example, I could reimplement connect():

bool Foo::connect(QObject *sender, const char *signal, QObject *receiver, const char *slot,...)
{
    // do something here, such as requesting a server to receive events that will cause the signal to be emitted
    return QObject::connect(sender, signal, receiver, slot);
}

Unfortunately it wouldn't work when the static QObject::connect() is used. Or I could reimplement QObject::metaObject() to return a custom QMetaObject subclass where indexOfSignal() is reimplemented but this also doesn't seem possible and indexOfSignal() is also not virtual.

Any ideas? Thanks.


Solution

  • See the connectNotify() virtual method in QObject, this is the one you should reimplement.