Qt简单屏幕截图(兼容Qt4/5)

  • Qt4使用QPixmap::grabWindow接口获取指定屏幕;
  • Qt5使用QScreen 的grabWindow接口获取指定屏幕;
  • QApplication::desktop()获取根窗口;
  • QUuid::createUuid()产生唯一ID;
  • pixmap.save(name)保存截图到本地.

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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文件

1
2
3
4
5
6
7
8
9
10
QT += core

equals(QT_MAJOR_VERSION, 5) : QT += widgets

CONFIG -= app_bundle
TARGET = Screenshot

TEMPLATE = app

SOURCES += main.cpp