PyQt Widget connect() and disconnect()
Try this:
from PyQt4 import QtGui as gui
app = gui.QApplication([])
myButton = gui.QPushButton()
def function_A():
myButton.clicked.disconnect() #this disconnect all!
myButton.clicked.connect(function_B)
print 'function_A'
def function_B():
myButton.clicked.disconnect(function_B) #this disconnect function_B
myButton.clicked.connect(function_A)
print 'function_B'
myButton.clicked.connect(function_A)
myButton.setText("Click me!")
myButton.show()
app.exec_()
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.).