Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a signal is connected to anything

Is there a way to tell if a signal is already connected to a function?

i.e I want to see if signals.siSelectionChange is connected to anything

signals.siSelectionChange.connect( self.SelAsSiAssets )
like image 913
Jay Avatar asked Nov 17 '11 11:11

Jay


2 Answers

You can use QObject.receivers to get the count of connected functions. I used it as follows, in the closeEvent() of a QWidget, I use as window:

    receiversCount = self.receivers(QtCore.SIGNAL("siSelectionChanged()"))
    if receiversCount > 0:
        self.sigChanged.disconnect()

Note that the signature in the argument string must match the real signature.

like image 150
alexisdm Avatar answered Oct 18 '22 00:10

alexisdm


Since I tried this with PyQt5 and it appears that there does not exist a QtCore.SIGNAL. I tried it with the isSignalConnected method of the QObject. An other problem you will face with this option is that there is no QMetaMethod.fromSignal in the PyQt5 library.

As result I wrote a getSignal function.

from PyQt5.QtCore import QMetaMethod
from PyQt5.QtCore import QObject

def getSignal (oObject : QObject, strSignalName : str):
    oMetaObj = oObject.metaObject()
    for i in range (oMetaObj.methodCount()):
        oMetaMethod = oMetaObj.method(i)
        if not oMetaMethod.isValid():
            continue
        if oMetaMethod.methodType () == QMetaMethod.Signal and \
            oMetaMethod.name() == strSignalName:
            return oMetaMethod

    return None


from PyQt5.QtCore import pyqtSignal

if __name__ == "__main__":
    class A (QObject):
        sigB = pyqtSignal()
        def __init__ (self):
            super().__init__()

    oA = A ()

    print ("is 'sigB' connected:", oA.isSignalConnected (getSignal(oA, "sigB")))

    oA.sigB.connect (lambda : print("sigB emitted!"))
    oA.sigB.emit()

    print ("is 'sigB' connected:", oA.isSignalConnected (getSignal(oA, "sigB")))

Output:

is 'sigB' connected: False
sigB emitted!
is 'sigB' connected: True
like image 4
leafar Avatar answered Oct 17 '22 23:10

leafar