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
738 views
in Technique[技术] by (71.8m points)

python - PyQt GUI order of operations

I have a following problem:

upon pressing a button in PyQt made GUI I have to do two actions:

  1. Immediately update a QTextBrowser
  2. Run a method that will wait for some time and enable some buttons after.

What I get is that 1 and 2 are done at the same time, after a waiting period.

Part of the code is:

    #in the signals definition...
    signalUpdateProgressDialog = QtCore.pyqtSignal(str) # signal definition

    #in the connections definition...
    self.btnStopOpt.clicked.connect(self.clickStop1)
    self.btnStopOpt.clicked.connect(self.clickStop)

def updateProgressDialog(self, dialog):
    self.ProgressDialog.setHtml(dialog)

def clickStop1(self):
    # notify
    self.signalUpdateProgressDialog.emit('Message')

def clickStop(self):

    # shut down thread...

    print "Thread Stopped"

    time.sleep(5)
    # enable run button
    self.btnRun.setEnabled(True)

I tried all in one clickStop method, I tried with and without emiting signal for updateProgress. Always, GUI is refreshed only after the waiting period.

Nevertheless, I encountered this problem before, I think I do not understand how it works with the GUI. In general, how to get the required behaviour: GUI is updated when the code line is executed?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The GUI is not updated/drawn until control is returned to the Qt event loop. The event loop runs in the main thread, and is what handles interactions with the GUI and coordinates the signals/slot system.

When you call a Qt function in a slot like clickStop1(), the Qt call runs, but the GUI is not redrawn immediately. In this case, control doesn't return to the event loop until clickStop() has finished running (aka all the slots for the clicked signal are processed.

The main problem with your code is that you have a time.sleep(5) in the main thread, which is blocking GUI interaction for the user as well as the redrawing. You should keep the execution time of slots short to maintain a responsive GUI.

I would thus suggest you modify clicked() so that it fires a singleshot QTimer after your specified timeout. QTimers do not block the main thread, and so responsiveness will be maintained. However, be aware that the user may interact with the GUI in the mean time! Make sure they can't compromise the state of your program with some user interaction while you wait for the QTimer to execute.


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

...