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