QGraphicsScene保存图片

QGraphicsScene保存图片

 1 import sys
 2 import time
 3 from PySide6.QtCore import *
 4 from PySide6.QtGui import *
 5 from PySide6.QtWidgets import *
 6 
 7 class MyQWidget(QWidget):
 8     def __init__(self, parent = ..., f = ...):
 9         super().__init__(parent, f)
10 
11         self.gs = QGraphicsScene()
12         rc = QGraphicsEllipseItem(QRect(20, 40, 400, 800))
13         self.gs.addItem(rc)
14         self.gv = QGraphicsView(self, scene=self.gs)
15 
16         self.btn = QPushButton()
17         self.btn.setText('保存图片')
18         self.btn.clicked.connect(self.button_clicked)
19 
20         self.ly = QVBoxLayout()
21         self.ly.addWidget(self.btn)
22         self.ly.addWidget(self.gv)
23 
24         self.setLayout(self.ly)
25 
26     def button_clicked(self):
27         pixmap = QPixmap(int(self.gs.width()), int(self.gs.height()))
28         pixmap.fill(Qt.GlobalColor.white)
29         painter = QPainter(pixmap)
30         self.gs.render(painter)
31         painter.end()
32         pixmap.save('./test.png')
33 
34 class MyMainWindow(QMainWindow):
35     def __init__(self, parent = ..., flags = ...):
36         super().__init__(parent, flags)
37 
38         self.centerWg = MyQWidget(self, Qt.WindowType.Widget)
39         self.setCentralWidget(self.centerWg)
40 
41 if '__main__' == __name__:
42     app = QApplication(sys.argv)
43     win = MyMainWindow(None, Qt.WindowType.Window)
44     win.setFixedSize(QSize(400, 300))
45     win.show()
46     sys.exit(app.exec())

 

posted @ 2024-12-17 17:03  hike_bug  阅读(20)  评论(0编辑  收藏  举报