Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQT force update textEdit before calling other function

Tags:

python

pyqt

pyqt5

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)
like image 354
Amos Egel Avatar asked Oct 24 '25 15:10

Amos Egel


1 Answers

The repaint is called in event loop so sleep the whole thread does not change anything.

You can call repaint manually by:

self.startDialogTextEdit.repaint()

or call static method:

QCoreApplication.processEvents()

which also call repaint internally

like image 71
Erik Šťastný Avatar answered Oct 26 '25 06:10

Erik Šťastný



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!