Resizing the QPainter canvas

When I resize the window, my QLabel Canvas is not resized, and the drawing coordinates are still coming from the window, not Canvas, so everything is shifted. (5.13.0 on Windows)

Any idea what’s wrong? Thanks

Adding self.setScaledContents(True) before self.setPixmap(pixmap) will make it fill the window regardless of size, but then it no longer paints.

It looks like there needs to be a SizePolicy. I got this code to work, based on this post on Stack Overflow.

I haven’t tried the other suggested method from the same post yet, and I can see from other sites that there are multiple ways of doing it.

I added to the Canvas class some scaling, a size policy, minimum size (needed to allow it to get smaller as well as larger), and resize event. It will also keep the aspect ratio and centres it. It resets the canvas. You can also see in this code 2 lines I commented out - that was where I was experimenting with making it fill the whole window regardless of size.

In addition, @martin has told me that you should be able to get the current pixmap from self.pixmap() (as in the mouseMoveEvent method) and then scale that directly, e.g.

def resizeEvent(self, event):
    pixmap = self.pixmap()
    pixmap=pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)

I hope this helps!

class Canvas(QtWidgets.QLabel):
	def init(self):
		pixmap= QtGui.QPixmap(600,300)
		#pixmap = QtGui.QPixmap(self.width(), self.height())
		pixmap=pixmap.scaled(self.width(),self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
		self.pen_color = QtGui.QColor('#000000')
		self.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)

	def set_pen_color(self, c):
		self.pen_color = QtGui.QColor(c)

	def mouseMoveEvent(self, e):
		painter = QtGui.QPainter(self.pixmap())
		p = painter.pen()
		for n in range(SPRAY_PARTICLES):
			xo = random.gauss(0, SPRAY_DIAMETER)
			yo = random.gauss(0, SPRAY_DIAMETER)
			painter.drawPoint(e.x() + xo, e.y() + yo)

	def resizeEvent(self, event):
		pixmap= QtGui.QPixmap(600,300)
		# pixmap = QtGui.QPixmap(self.width(),self.height())
		pixmap=pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)