文章目录
- 0 环境
- 1 简介
- 2 QScreen 类
- 2.1 获取 QScreen 的对象
- 2.2 QScreen 的常见信息
- 3. 示例代码
0 环境
- Python 3.12.1
- PyQt6 6.6.1 ' pip install PyQt6 'PyQt6-Qt6 6.6.1 默认安装PyQt6-sip 13.6.0 默认安装
1 简介
屏幕截图的方法: 使用 【PyQt6】的 QScreen.grabWindow() 方法
def grabWindow(self, WId=0, x, y, width, height) -> QPixmap:
WId: 窗口系统标识符, 默认 0 表示 屏幕将被抓取
偏移: x, y,
大小: width, height
如果想要全屏截图, 连参数都不需要写
screen = QApplication.primaryScreen()pixmap = screen.grabWindow()pixmap.save('123.png') # 可以直接保存为文件, qt 会根据扩展名 保存成不同的格式
2 QScreen 类
2.1 获取 QScreen 的对象
QScreen 不能被实例化,只能从 QGuiApplication 来获取
class QGuiApplication(QtCore.QCoreApplication):
...@staticmethoddef screens() -> typing.List['QScreen']: # 多个屏幕 ,可以用这个方法进行检索@staticmethoddef primaryScreen() -> typing.Optional['QScreen']: # 主屏幕
...
2.2 QScreen 的常见信息
def screen_info():"""打印屏幕的信息,包括名称/厂家/当前分辨率/刷新率/yiArgs:screen: QScreen 类型"""screen = QApplication.primaryScreen()print('screen.name', screen.name())print('screen.manufacturer', screen.manufacturer())print('screen.refreshRate', screen.refreshRate())print('screen.size', screen.size())print('screen.availableSize', screen.availableSize())print('screen.devicePixelRatio', screen.devicePixelRatio())
3. 示例代码
在 Qt 中 直接使用 QLabel 显示像素图比较方便
如果需要使用 opencv 和 matplotlib 来显示的话, 需要把像素图转成 ndarray 类型
from PyQt6.QtWidgets import QApplication, QLabeldef screen_info():"""打印屏幕的信息,包括名称/厂家/当前分辨率/刷新率/yiArgs:screen: QScreen 类型"""screen = QApplication.primaryScreen()print('screen.name', screen.name())print('screen.manufacturer', screen.manufacturer())print('screen.refreshRate', screen.refreshRate())print('screen.size', screen.size())print('screen.availableSize', screen.availableSize())print('screen.devicePixelRatio', screen.devicePixelRatio())def grabFullScreen():screen = QApplication.primaryScreen()pixmap = screen.grabWindow()return pixmapif __name__ == '__main__':qApp = QApplication([])screen_info()pixmap = grabFullScreen()pixmap.save('123.png')w = QLabel()w.resize(pixmap.width()//3, pixmap.height()//3)w.setScaledContents(True)w.setPixmap(pixmap)w.show()qApp.exec()