有没有办法判断信号是否已连接到某个功能?
即我想查看signals.siSelectionChange是否连接到任何
signals.siSelectionChange.connect( self.SelAsSiAssets )
答案 0 :(得分:10)
您可以使用QObject.receivers
来获取已连接功能的计数。我用它如下,在QWidget的closeEvent()
中,我用作窗口:
receiversCount = self.receivers(QtCore.SIGNAL("siSelectionChanged()"))
if receiversCount > 0:
self.sigChanged.disconnect()
请注意,参数字符串中的签名必须与真实签名匹配。
答案 1 :(得分:1)
因为我在 PyQt5 上尝试过这个,但似乎不存在 QtCore.SIGNAL
。我用 QObject 的 isSignalConnected
方法进行了尝试。使用此选项将面临的另一个问题是 PyQt5 库中没有 QMetaMethod.fromSignal
。
结果我写了一个 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