I have a QT class instance, called C, (C inherits QOBJECT) that sends a signal S.
In my program, other QT classes instances X are created and destroyed when the program runs. These other classes connect and disconnect S, i.e. they run:
connect(C,SIGNAL(S()), this, SLOT(my_func())); // <this> is an instance of X
or
disconnect(C,SIGNAL(S()), this, SLOT(my_func()));
In class C, the calculation of whether S should be emitted (and the data associated to it – not shown here) is rather complicated, so I would like the instance of class C (which emits the signal) to be notified when one(or more) object are connected (listening) to S or when all are disconnected.
I have read about the connectNotify and disconnectNotify functions, but their usage is discouraged. Besides the documentation does not state very clearly if there is a one to one relationship between the number of (dis)connectNotify calls and the number of “listener” to the signal (or can one single connectNotify be called for more than one listener?).
Can I just count positively (count++) the number of connectNotify and negatively (count–) the number of disconnectNotify and just react to non-zero value?
Any better way to do this?
First, I think you’ve got it right that
connectNotifyanddisconnectNotifycan be used for this purpose – eachconnectevent will be counted properly, even if it is a duplicate from the same object.You can also double check this with QObject::receivers
My suggestion would be to write a simple test program. Override
connectNotifyanddisconnectNotifyto increment/decrement a counter, but also usereceiversto verify that the counter is correct. Try connecting multiple times, disconnecting multiple times, disconnecting even if there is no connection, etc.Something to be careful of:
connectanddisconnectare thread-safe; I’m not sure if the matchingNotifyfunctions are safe also.