Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
814 views
in Technique[技术] by (71.8m points)

python - PyQt Widget connect() and disconnect()

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...