PyQt Widget connect() and disconnect()(PyQt Widget connect() 和 disconnect())
问题描述
根据条件,我想将按钮连接/重新连接到不同的功能.
假设我有一个按钮:
myButton = QtGui.QPushButton()
在这个例子中,假设我检查是否有互联网连接.
如果连接==真:myButton.clicked.connect(function_A)elif 连接 == False:myButton.clicked.connect(function_B)
首先,在按钮被重新分配/重新连接到另一个功能(功能_A 或功能_B)之前,我想将按钮与它已经连接的任何功能断开连接.其次,我已经注意到,重新连接按钮后,需要额外单击按钮才能选择新功能.按钮重新连接到另一个功能后,它仍会尝试运行前一个功能 - 按钮先前(重新连接之前)连接到的功能.请指教.提前致谢!
稍后
似乎小部件的 .disconnect() 方法可用于将按钮与其连接的功能断开连接.
myButton.disconnect()
不幸的是,如果小部件未连接到任何函数,.disconnect() 会抛出错误.为了解决这个问题,我使用了 Try/Except.但我宁愿使用更优雅的解决方案...
尝试:myButton.clicked.disconnect()除了例外:通过
如果你需要在很多地方重新连接信号,那么你可以定义一个通用的效用函数,如下所示:
def reconnect(signal, newhandler=None, oldhandler=None):尝试:如果 oldhandler 不是 None:而真:signal.disconnect(oldhandler)别的:信号断开()除了类型错误:经过如果 newhandler 不是 None:信号.connect(newhandler)...如果连接:重新连接(myButton.clicked,function_A)别的:重新连接(myButton.clicked,function_B)
(注意:安全断开特定处理程序需要循环,因为它可能已连接多次,并且 disconnect(slot)
一次仅删除一个连接.).>
Depending on a conditions I would like to connect/re-connect a button to a different function.
Let's say I have a button:
myButton = QtGui.QPushButton()
For this example let's say I check if there is an internet connection.
if connected == True:
myButton.clicked.connect(function_A)
elif connected == False:
myButton.clicked.connect(function_B)
First of all I would like to disconnect a button from any function it was already connected before the button is being re-assigned/re-connected to another function (function_A or function_B). Secondly, I have already noticed that after the button is re-connected it takes an extra click for the button to pick up a new function. After the button is re-connected to another function it still attempts to run a previous function - a function to which a button was connected earlier (before a re-connection). Please advice. Thanks in advance!
EDITED LATER:
It appears a widget's .disconnect() method can be used to disconnect a button from a function it it is connected.
myButton.disconnect()
Unfortunately .disconnect() throws an error if a widget is not connected to any function. To get around it I am using Try/Except. But I would rather use a more elegant solution...
try: myButton.clicked.disconnect()
except Exception: pass
If you need to reconnect signals in many places, then you could define a generic utility function like this:
def reconnect(signal, newhandler=None, oldhandler=None):
try:
if oldhandler is not None:
while True:
signal.disconnect(oldhandler)
else:
signal.disconnect()
except TypeError:
pass
if newhandler is not None:
signal.connect(newhandler)
...
if connected:
reconnect(myButton.clicked, function_A)
else:
reconnect(myButton.clicked, function_B)
(NB: the loop is needed for safely disconnecting a specific handler, because it may have been connected multple times, and disconnect(slot)
only removes one connection at a time.).
这篇关于PyQt Widget connect() 和 disconnect()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!