5

有没有办法判断一个信号是否已经连接到一个函数?

即我想看看 signals.siSelectionChange 是否连接到任何东西

signals.siSelectionChange.connect( self.SelAsSiAssets )
4

2 回答 2

11

您可以使用QObject.receivers来获取连接函数的计数。我按如下方式使用它,在closeEvent()QWidget 中,我用作窗口:

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

请注意,参数字符串中的签名必须与真实签名匹配。

于 2011-11-17T12:10:08.503 回答
2

因为我用 PyQt5 试过这个,但似乎不存在QtCore.SIGNAL. 我用isSignalConnectedQObject的方法试了一下。使用此选项您将面临的另一个问题是QMetaMethod.fromSignalPyQt5 库中没有。

结果我写了一个getSignal函数。

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

输出:

is 'sigB' connected: False
sigB emitted!
is 'sigB' connected: True
于 2021-08-02T12:41:56.797 回答