项目中我们常用到截取屏幕,Qt给我的们多种方式:
主要有以下三种:
截取全屏;截取控件为图片;指定位置截屏三种截屏方式;
1.截取全屏
常用:
实现:
QScreen *screen = QGuiApplication::primaryScreen();
screen->grabWindow(0).save("./picture.png", "png");
2.截取控件为图片
实现:
QScreen *screen = QGuiApplication::primaryScreen();
auto rect = ui->calendarWidget->rect();
auto widgetScreenPic = screen->grabWindow(ui->calendarWidget->winId(), rect.x(), rect.y(), rect.width(), rect.height());
widgetScreenPic = widgetScreenPic.scaled(QSize(rect.width(), rect.height()), Qt::KeepAspectRatio);
widgetScreenPic.save("./widgetpicture.png");
上面这种方式对造成我的布局显示有问题,改为在全屏上截取控件的范围
QScreen *screen = QGuiApplication::primaryScreen();
auto rect = ui->calendarWidget->rect();
QPoint globalPos = ui->calendarWidget->mapToGlobal(QPoint(0, 0));
//auto widgetScreenPic = screen->grabWindow(ui->calendarWidget->winId(), rect.x(), rect.y(), rect.width(), rect.height());
auto widgetScreenPic = screen->grabWindow(0, globalPos.x(), globalPos.y(), rect.width(), rect.height());
widgetScreenPic = widgetScreenPic.scaled(QSize(rect.width(), rect.height()), Qt::KeepAspectRatio);
widgetScreenPic.save("./widgetpicture.png");
3.指定范围截屏:
实现:
QPixmap p = this->grab(QRect(-20, -20, 200, 500));
p.save("./Rectpicture.png","png");