Skip to main content
 首页 » 编程设计

python之PyQt 如何将 QPainterPath 转换为 QPixmap

2024年12月31日25mate10pro

我一直在网上搜索,但找不到执行此操作的好方法。我需要将 QPainterPath 转换为 QPixmap。这可能吗?如果是,这将如何完成?谢谢!

请您参考如下方法:

我的想法不是将 QPainterPath 转换为 QPixmap,而是在 QPixmap 中绘制 QPainterPath,如下所示:

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_())