Clearing the canvas in QPainter

Virginia | 2020-05-10 20:26:36 UTC | #1

My canvas is not clearing every time I run the app. I tried adding update() to the code but it doesn't seem to work. Please can you help me figure out what I am doing wrong? Your previous tutorials have all been great, but this one is lacking a little bit of detail.


martin | 2020-05-10 20:26:57 UTC | #2

When you say it's not clearing, what do you mean exactly? Is it appearing black maybe? It could be that you need to fill the canvas with white to begin with, can you try add the following canvas fill line?

python
canvas = QtGui.QPixmap(400, 300)
canvas.fill(QtGui.QColor('#ffffff')) # Fill entire canvas.

(Also, which version of PyQt5 are you using, and which platform?)


Virginia | 2020-05-10 20:27:47 UTC | #3

Thank you for your reply. I figured out that if I add self.update() after painter.end() in all my functions the canvas does clear. I'm using the most recent version of pyqt5 on Windows 10 with Spyder.

PyQt/PySide 1:1 Coaching with Martin Fitzpatrick — Save yourself time and frustration. Get one on one help with your Python GUI projects. Working together with you I'll identify issues and suggest fixes, from bugs and usability to architecture and maintainability.

Book Now 60 mins ($195)

Since it's Windows I also have a black background, so I've been changing the pen colour. I really appreciate the code to change the background - I searched all over the web for the code to do that but couldn't find anything relevant to pyqt5 and the background in this particular situation. Now it looks like I don't need to call self.update() if I have the background filled.

Packaging Python Applications with PyInstaller by Martin Fitzpatrick — This step-by-step guide walks you through packaging your own Python applications from simple examples to complete installers and signed executables.

More info Get the book


Over 10,000 developers have bought Create GUI Applications with Python & Qt!
Create GUI Applications with Python & Qt6
Take a look

Downloadable ebook (PDF, ePub) & Complete Source code

Also available from Leanpub and Amazon Paperback

Mark As Complete
Martin Fitzpatrick

Clearing the canvas in QPainter was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt. Martin founded PythonGUIs to provide easy to follow GUI programming tutorials to the Python community. He has written a number of popular Python books on the subject.