Qt5 - why not screenshot and saving to a file?

  • 9 months ago
Comment

ChatGPT
1 / 1

Taking a screenshot and saving it to a file using Qt5 involves using the QScreen and QPixmap classes. Below is an example of how you can capture the screen content and save it to an image file using Qt:

cpp
#include <QtWidgets/QApplication>
#include <QtGui/QScreen>
#include <QtGui/QPixmap>
#include <QDateTime>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

// Capture the screen content
QScreen *screen = QGuiApplication::primaryScreen();
QPixmap screenshot = screen->grabWindow(0); // 0 means the whole screen

// Save the screenshot to a file
QString filename = "screenshot_" + QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss") + ".png";
screenshot.save(filename);

return 0;
}

In this example:

  • We use QScreen *screen = QGuiApplication::primaryScreen(); to get a pointer to the primary screen.
  • screen->grabWindow(0) captures the content of the whole screen. You can provide the window ID if you want to capture a specific window.
  • We use QPixmap to store the screenshot.
  • We generate a unique filename using the current date and time.
  • screenshot.save(filename); saves the screenshot to the specified file.

Make sure you have added the necessary Qt modules (e.g., QtWidgets and QtGui) to your project's .pro file or CMake configuration.

Keep in mind that this is a simple example, and you might need to handle error cases and explore additional features provided by Qt, such as customizing the captured region, capturing specific windows, handling different image formats, and handling different screen scaling factors.