如何从 lambda 插槽断开信号?
How to disconnect a signal from a slot which is a lambda?
假设插槽接受一个参数,例如,
self._nam = QtNetwork.QNetworkAccessManager(self)
# ...
response = self._nam.get(request)
self.timer.timeout.connect(lambda: self.on_reply_finished(response))
信号怎么会和slot断开?下面报错Failed to disconnect signal timeout().
:
self.timer.timeout.disconnect(lambda: self.on_reply_finished(response))
是否因为 lambda 不是 'real' 插槽而是 Python 技巧?在那种情况下,如何将响应参数传递给插槽(而不使 response
成为成员)?
谢谢
不是,因为这两个lambda不是同一个对象
您需要将与在 connect
方法中使用的相同的引用传递给 disconnect
方法。如果您使用匿名 lambda 函数,除了在信号上调用 disconnect()
(不带参数)之外,没有其他方法可以断开它,但这将断开 所有 连接的信号。
仅当您传递相同的 lambda 时:
self._on_timeout = lambda: self.on_reply_finished(response)
self.timer.timeout.connect(self._on_timeout)
# ...
self.timer.timeout.disconnect(self._on_timeout)
您可能想将功能附加到计时器:
self.timer.on_timeout = lambda: self.on_reply_finished(response)
self.timer.timeout.connect(self.timer.on_timeout)
# ...
self.timer.timeout.disconnect(self.timer.on_timeout)
顺便说一句,你 can use functools.partial
而不是 lambda。
假设插槽接受一个参数,例如,
self._nam = QtNetwork.QNetworkAccessManager(self)
# ...
response = self._nam.get(request)
self.timer.timeout.connect(lambda: self.on_reply_finished(response))
信号怎么会和slot断开?下面报错Failed to disconnect signal timeout().
:
self.timer.timeout.disconnect(lambda: self.on_reply_finished(response))
是否因为 lambda 不是 'real' 插槽而是 Python 技巧?在那种情况下,如何将响应参数传递给插槽(而不使 response
成为成员)?
谢谢
不是,因为这两个lambda不是同一个对象
您需要将与在 connect
方法中使用的相同的引用传递给 disconnect
方法。如果您使用匿名 lambda 函数,除了在信号上调用 disconnect()
(不带参数)之外,没有其他方法可以断开它,但这将断开 所有 连接的信号。
仅当您传递相同的 lambda 时:
self._on_timeout = lambda: self.on_reply_finished(response)
self.timer.timeout.connect(self._on_timeout)
# ...
self.timer.timeout.disconnect(self._on_timeout)
您可能想将功能附加到计时器:
self.timer.on_timeout = lambda: self.on_reply_finished(response)
self.timer.timeout.connect(self.timer.on_timeout)
# ...
self.timer.timeout.disconnect(self.timer.on_timeout)
顺便说一句,你 can use functools.partial
而不是 lambda。