[英]How to render a part of QGraphicsScene and save It as image file PyQt5
Suppose I have QGraphicsPixmapItem
from loaded image which is added to QGraphicsScene
.假设我有来自加载图像的
QGraphicsPixmapItem
添加到QGraphicsScene
。 And suppose I'll add several QGraphicsPolygonItem
's on scene.假设我会在现场添加几个
QGraphicsPolygonItem
。 How I can render a part of the scene as full-size image both with polygons that are not in blank area and save this area as image file.如何将场景的一部分渲染为全尺寸图像,同时使用不在空白区域的多边形并将该区域保存为图像文件。
class ImageView(QtWidgets.QGraphicsView):
def __init__(self, parent):
super(ImageView, self).__init__(parent)
self.setFocus()
self._zoom = 0
self._empty = True
self.scene = QtWidgets.QGraphicsScene(self)
self._image = QGraphicsPixmapItem()
self.scene.addItem(self._image)
self.setScene(self.scene)
# some other actions
foo()
def fitInView(self):
# custom fit in view and scaling
bar()
# some other methods
class MainWindow(QtWidgets.QWidget):
def __init__(self):
self.viewer = ImageView(self)
foo()
def _save_image(self):
# method that I need to implement
pass
Untested, but using QGraphicsScene::render
you should be able to do something like...未经测试,但使用
QGraphicsScene::render
你应该能够做类似的事情......
def _save_image(self):
# Get region of scene to capture from somewhere.
area = get_QRect_to_capture_from_somewhere()
# Create a QImage to render to and fix up a QPainter for it.
image = QImage(area.size(), QImage.Format_ARGB32_Premultiplied)
painter = QPainter(image)
# Render the region of interest to the QImage.
self.scene.render(painter, image.rect(), area)
painter.end()
# Save the image to a file.
image.save("capture.png")
I wanted to add that render requires the QRectF object for the image.area() and area parameters, otherwise it throws a TypeError.我想添加该渲染需要 image.area() 和 area 参数的 QRectF 对象,否则它会引发 TypeError。
I did:我做了:
QtCore.QRectF(image.rect())
and created a QRectF object for the area parameter.并为 area 参数创建了一个 QRectF 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.