如何渲染QGraphicsScene的一部分并将其另存为图像文件PyQt5

时间:2018-10-26 08:43:05

标签: python pyqt pyqt5 qgraphicsview qgraphicsscene

假设加载的图像中有QGraphicsPixmapItem,该图像已添加到QGraphicsScene中。并假设我将添加几个QGraphicsPolygonItem。我如何将场景的一部分呈现为全尺寸图像,并且具有不在空白区域中的多边形,并且将该区域保存为图像文件。 strong>

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

GUI Example

1 个答案:

答案 0 :(得分:0)

未经测试,但是使用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")