Search code examples
qtqt6

Is it possible to set a clip path on a QImage or save what a Qpainter paints?


I have a QImage I am able to clip out a QRegion of and successfully clip out the region using the QPainter class setClipRegion() function. However, I want to save what is drawn as a new QImage but am not seeing anything in the docs about saving what is actually displayed.

I've tried directly changing the images alpha channel to match the clipping region but my implementation is very inefficient. The setClipRegion() function was the only thing I learned that could efficiently display what I wanted. My end goal is to use the clipped image as a QOpenGLTexture so I somehow need to save the originally clipped image. Thanks for any help.


Solution

  • You can simply specify a new file name when saving. so you do not overwrite the old one.

        image = QtGui.QImage('orginal.png')
        output = QtGui.QImage(image.size(), QtGui.QImage.Format_ARGB32)
        output.fill(QtCore.Qt.transparent)
        painter = QtGui.QPainter(output)
    ....
        -> your clip path
    ....
        painter.drawImage(QtCore.QPoint(), image)
        painter.end()
        output.save('new.png')