Pyside setText() not updating QLabel

2019-09-14 01:49发布

问题:

I have the following:

 self.testTxt = QtGui.QLabel("0")
 .
 .
 for i in range(10):
        sleep(1)
        self.testTxt.setText(unicode(i))

but the QLabel doesn't get updated till the end of the loop

I've tried:

self.processEvents()
self.testTxt.update()

But to no avail.

Does anyone happen to know why?

Thanks in advance

回答1:

The text box does not update because the program is tied up inside the for loop and thus never gets back to Qt's event loop to redraw the widget. Calling testTxt.update() does not help because, as the QWidget documentation states, update() simply schedules a repaint for the next time the event loop is run (and this is taken care of when you call setText anyway).

Possible solutions:

  • Use QTimer to make repeated calls to a function that updates the text (this is the preferred solution)
  • call testText.repaint() after every call to setText
  • call QApplication.processEvents() after every call to setText


标签: python qt pyside