Refreshing a QWidget

Olivier Giniaux picture Olivier Giniaux · Jun 9, 2015 · Viewed 39.2k times · Source

I've been having this issue a lot of times.

When I modify some properties of a QWidget after the widget.show(), the widget won't update. Most of the time, a mouse click or when the mouse leaves or enters the widget, the widget will be updated. However, if I leave the mouse, it won't refresh by itself.

Until now I managed to deal with this by doing :

widget.hide()
widget.show()

But this is a very dirty fix. Is there a better way to tell python to refresh the widget ?

Thank you.

Answer

Kosovan picture Kosovan · Jun 9, 2015

To update the widget, you should repaint() it, but calling repaint() directly is not very good, so try:

widget.update()

From doc:

This function does not cause an immediate repaint; instead it schedules a paint event for processing when Qt returns to the main event loop. This permits Qt to optimize for more speed and less flicker than a call to repaint() does.

Calling update() several times normally results in just one paintEvent() call.

Qt normally erases the widget's area before the paintEvent() call. If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is responsible for painting all its pixels with an opaque color.