Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

python - 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. And suppose I'll add several QGraphicsPolygonItem's on scene. 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

GUI Example

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Untested, but using QGraphicsScene::render you should be able to do something like...

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...