PyQt how to convert a QPainterPath to a QPixmap?

786 views Asked by At

I've been searching online and couldn't find a good way to do this. I need to convert a QPainterPath to a QPixmap. Is this possible? If yes, how would this be done? Thanks!

1

There are 1 answers

0
eyllanesc On BEST ANSWER

The idea is not to convert a QPainterPath to QPixmap but to draw a QPainterPath in a QPixmap as I show below:

from PyQt5 import QtCore, QtGui, QtWidgets

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)

    adjust_to_content = True

    path = QtGui.QPainterPath()
    path.addRect(20, 20, 60, 60)
    path.moveTo(0, 0)
    path.cubicTo(99, 0,  50, 50,  99, 99)
    path.cubicTo(0, 99,  50, 50,  0, 0)

    r = path.boundingRect()
    s = r.size().toSize()
    pixmap = QtGui.QPixmap(s if adjust_to_content else QtCore.QSize(640, 480))
    pixmap.fill(QtCore.Qt.white)
    painter = QtGui.QPainter(pixmap)
    painter.setRenderHint(QtGui.QPainter.Antialiasing)
    painter.setPen(QtGui.QPen(QtGui.QColor("green")))
    painter.translate(-r.topLeft())
    painter.drawPath(path)
    painter.end()

    label = QtWidgets.QLabel(pixmap=pixmap, alignment=QtCore.Qt.AlignCenter)
    label.show()
    sys.exit(app.exec_())

enter image description here