方法1
- 接口:
QPixmap QScreen::grabWindow(WId window, int x = 0, int y = 0, int width = -1, int height = -1)
- 示例:
QScreen *screen = QGuiApplication::primaryScreen(); screen->grabWindow(0).save("screen_shot.jpg", "jpg"); // 0值为整个电脑屏幕WId
- 可以通过设置x,y坐标位置和width,height的大小来截图。
方法2
- 接口:
QPixmap QWidget::grab(const QRect &rectangle = QRect(QPoint(0, 0), QSize(-1, -1)))
- 示例:
QWidget widget; widget.grab().save("screen_shot.jpg", "jpg");
- 和QScreen的grabWindow一样可以通过设置坐标位置和窗口的大小来截图。
main.cpp
#include <QApplication> #include <QDesktopWidget> #include <QScreen> #include <QPixmap> #include <QUuid> #include <QDateTime> int main(int argc, char *argv[]) { QApplication a(argc, argv); #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) QPixmap pixmap = QPixmap::grabWindow(QApplication::desktop()->winId()); #else if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) QScreen *screen = QGuiApplication::primaryScreen(); QPixmap pixmap = screen->grabWindow(QApplication::desktop()->winId()); #endif QString name = QString("%1-%2.png"). arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")). arg(QUuid::createUuid().toString()); pixmap.save(name); return 0; }
qmake文件
QT += core equals(QT_MAJOR_VERSION, 5) : QT += widgets CONFIG -= app_bundle TARGET = Screenshot TEMPLATE = app SOURCES += main.cpp