PyQt QGraphicsView组件视图导出为图片
可以通过调用QGraphicsView.render()接口将组件视图渲染到QPixmap或QImage上,再调用QPixmap或QImage的**save()**方法保存为图片
rect = QGraphicsView.viewport(self.dlg.gvPointRecords).rect()
pixmap = QPixmap(rect.size())
painter = QPainter(pixmap)
painter.begin(pixmap)
self.dlg.gvPointRecords.render(painter, QRectF(pixmap.rect()), rect)
painter.end()
if self.imgFile:
imgFile, _ = QFileDialog.getSaveFileName(self.dlg, "保存图像", os.path.dirname(self.imgFile),
"影像 (*.png *.jpg)")
else:
imgFile, _ = QFileDialog.getSaveFileName(self.dlg, "保存图像", './', "影像 (*.png)")
if imgFile:
img = pixmap.save(imgFile)
self.imgFile = imgFile
代码的关键在于一定不能少了painter.begin(pixmap)和painter.end(),否则图片虽然可以导出,但程序会崩溃,而且不容易排查错误出现在哪里