使用Qt来抓图截屏,需要用到QPixmap 来保存图片,也可以设置定时器,设置间隔xx时间捕获一次屏幕。
1、需要用到的主要头文件
#include<QPixmap>
#include <QDesktopWidget>
2、获取整个桌面图像
QScreen *screen=QApplication::primaryScreen(); //获取当前程序的主窗口对象
QPixmap fullScreenPixmap = screen->grabWindow(QApplication::desktop()->winId()); //调用主窗口对象的捕捉窗口图像,并传递桌面窗口的id号
fullScreenPixmap.save("datas/fullScreenPixmap.jpg"); //保存图像
cout<<"finished save picture"<<endl;
3、截取当前窗口(即程序运行窗口)
QPixmap currentScreenPixmap=QPixmap::grabWindow(QApplication::desktop()->winId(),pos().x()+8,pos().y()+90,frameGeometry().width()-16,frameGeometry().height()-120); //捕获当前窗口
currentScreenPixmap.save("datas/currentScreenPixmap.jpg");
说明;pos().x(),pos().y()表示需要截取的起始点坐标;,frameGeometry().width(),frameGeometry().height()表示需要截取窗口的大小。也可以根据需要进行加减某个值。
4、实现函数
//截取屏幕图像并保存
void MainWindow::screenShort()
{
QScreen *screen=QApplication::primaryScreen(); //获取当前程序的主窗口对象
QPixmap fullScreenPixmap = screen->grabWindow(QApplication::desktop()->winId(),300,150,700,400); //调用主窗口对象的捕捉窗口图像,并传递桌面窗口的id号
QPixmap currentScreenPixmap=QPixmap::grabWindow(QApplication::desktop()->winId(),pos().x()+8,pos().y()+90,frameGeometry().width()-16,frameGeometry().height()-120); //捕获当前窗口
fullScreenPixmap.save("datas/fullScreenPixmap.jpg"); //保存图像
currentScreenPixmap.save("datas/currentScreenPixmap.jpg");
cout<<"finished save picture"<<endl;
}