Python - How to save canvas in pyqt5?

Python - How to save canvas in pyqt5?

In PyQt5, you can save the contents of a QGraphicsScene or any QWidget that inherits from QPaintDevice to an image file. If you have drawn on a QCanvas and want to save this as an image, here is how you can do it:

If your canvas is a QGraphicsView:

from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QApplication from PyQt5.QtCore import QRectF from PyQt5.QtGui import QImage, QPainter # ... setup your QGraphicsScene and QGraphicsView ... app = QApplication([]) scene = QGraphicsScene() view = QGraphicsView(scene) # ... draw on your scene ... # Now, to save the scene's content as an image image = QImage(view.viewport().size(), QImage.Format_ARGB32) image.fill(Qt.white) # Assuming you want a white background for areas not drawn on painter = QPainter(image) view.render(painter, QRectF(image.rect()), view.viewport().rect()) painter.end() image.save("filename.png", "PNG") # Save as PNG, you can choose other formats like JPG 

If you are referring to a QWidget derived canvas where you perform custom painting:

from PyQt5.QtWidgets import QWidget, QApplication from PyQt5.QtGui import QPainter, QImage class MyCanvas(QWidget): # ... your widget with painting ... def save_canvas(self, filename): image = QImage(self.size(), QImage.Format_ARGB32) image.fill(Qt.white) # or another background color painter = QPainter(image) self.render(painter) painter.end() image.save(filename) app = QApplication([]) canvas = MyCanvas() # ... do your drawing on the canvas ... # When you want to save it: canvas.save_canvas("canvas_image.png") 

In both cases, QPainter is used to paint the contents of the widget onto an QImage, which is then saved to a file with QImage.save() method. You can specify the filename and the format you want to save in (e.g., PNG, JPG).

You would call canvas.save_canvas("filename.png") at the point in your code where you want to save the current view of the canvas to an image. This might be in response to a user action like clicking a button.


More Tags

redux-saga git recaptcha-v3 edit aws-sdk-nodejs git-pull browserify twitter-bootstrap image-rotation devops

More Programming Guides

Other Guides

More Programming Examples