欢迎访问宙启技术站
智能推送

PyQtGraphQt.QtGui.QMainWindow实现窗口的截屏和图像保存功能

发布时间:2023-12-13 12:42:12

PyQtGraph是一个基于PyQt和numpy的图形绘制库,它支持图像绘制、曲线绘制、散点图绘制等多种功能。在PyQtGraph中,可以使用QtGui.QMainWindow类创建一个主窗口,并在该窗口上实现图像的截屏和保存功能。

首先,我们需要安装PyQtGraph库。可以使用以下命令来安装:

pip install pyqtgraph

下面是一个使用PyQtGraph实现截屏和图像保存功能的例子:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QPainter
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QPushButton
import pyqtgraph as pg

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("Screenshot and Save Example")
        self.setGeometry(100, 100, 800, 600)
        
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        
        self.layout = QVBoxLayout(self.central_widget)
        self.label = QLabel(self)
        self.layout.addWidget(self.label)
        
        self.plot_widget = pg.PlotWidget()
        self.layout.addWidget(self.plot_widget)
        
        self.btn_screenshot = QPushButton("Screenshot")
        self.layout.addWidget(self.btn_screenshot)
        self.btn_screenshot.clicked.connect(self.screenshot)
        
        self.btn_save = QPushButton("Save")
        self.layout.addWidget(self.btn_save)
        self.btn_save.clicked.connect(self.save_image)
        
    def screenshot(self):
        # 获取主窗口的尺寸
        size = self.size()
        # 设置一个空的QPixmap对象
        pixmap = QPixmap(size)
        # 使用QPainter在pixmap上进行绘制
        painter = QPainter(pixmap)
        # 调用主窗口的绘制函数,将主窗口绘制到pixmap上
        self.render(painter)
        painter.end()
        # 将pixmap显示在label上
        self.label.setPixmap(pixmap)
        
    def save_image(self):
        # 弹出保存文件对话框
        filename, _ = pg.Qt.QtWidgets.QFileDialog.getSaveFileName(self, "Save Image", "", "Image Files(*.png *.jpg)")
        if filename:
            # 获取主窗口的尺寸
            size = self.size()
            # 设置一个空的QPixmap对象
            pixmap = QPixmap(size)
            # 使用QPainter在pixmap上进行绘制
            painter = QPainter(pixmap)
            # 调用主窗口的绘制函数,将主窗口绘制到pixmap上
            self.render(painter)
            painter.end()
            # 保存pixmap为图片文件
            pixmap.save(filename)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

在上面的例子中,我们创建了一个继承自QMainWindow的MainWindow类。在主窗口上添加了一个Label用来显示截屏的图像,一个PlotWidget用来显示图像,并添加了两个按钮 "Screenshot" 和 "Save"。点击 "Screenshot" 按钮时,会调用screenshot方法将主窗口的图像截屏并显示在Label上。点击 "Save" 按钮时,会弹出保存文件对话框,用户可以选择保存的文件名和文件格式,然后调用save_image方法将主窗口的图像保存为指定的文件。

以上就是使用PyQtGraph实现窗口的截屏和图像保存功能的例子。通过使用QWidget、QMainWindow和PyQtGraph的绘图功能,我们可以方便地实现图像的截屏和保存。