Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - PyQT force update textEdit before calling other function

My question concerns PyQT5. I try to have a dialog window with a button that when clicked

  1. updates some text of a QTextEdit field
  2. calls a function (which needs much time to terminate)

Something like this:

class StartDialog(QtWidgets.QWidget, start_dialog_ui.Ui_Dialog):
  def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.OKButton.clicked.connect(self.start)

 def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    run_lengthy_function(self)

However, when I run my GUI I notice that the text is updated only after the lengthy function has terminated, although the QTextEdit.append is called before the lengthy function. How can I enforce that the text is updated in advance?

What I tried so far (but didn't work) was to let Python wait some time before triggering the lengthy function call, i.e.

from time import sleep

class StartDialog(QtWidgets.QWidget, start_dialog_ui.Ui_Dialog):
  def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.setupUi(self)
    self.OKButton.clicked.connect(self.start)

 def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    sleep(5)
    run_lengthy_function(self)
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The solution for the case that the text is displayed in the QTextEdit is to call qApp.processEvents(), this force to the GUI update:

def start(self):
    self.startDialogTextEdit.append("simulation running ...")
    QtWidgets.qApp.processEvents()
    [...]

On the other hand if the task is heavy it may be blocking the GUI, so maybe one solution is to run it on another thread, I can not give a proper recommendation since I do not know your function


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...