Search code examples
c++windowsqtqt5qpixmap

Qt5 - why not screenshot and saving to a file?


Why its not saving any file?

#include "mainwindow.h"
#include <QApplication>
#include <QPixmap>
#include <QPainter>
#include <QList>
#include <QScreen>


QPixmap grabScreens() {
  auto screens = QGuiApplication::screens();
  QList<QPixmap> scrs;
  int w = 0, h = 0, p = 0;
  foreach (auto scr, screens) {
    QPixmap pix = scr->grabWindow(0);
    w += pix.width();
    if (h < pix.height()) h = pix.height();
    scrs << pix;
  }
  QPixmap final(w, h);
  QPainter painter(&final);
  final.fill(Qt::black);
  foreach (auto scr, scrs) {
    painter.drawPixmap(QPoint(p, 0), scr);
    p += scr.width();
  }
  return final;
}


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

    QPixmap pixmap = grabScreens();

    QFile file("file.jpg");
    file.open(QIODevice::WriteOnly);
    pixmap.save(&file, "JPG", 1);

    MainWindow w;
    w.show();

    return a.exec();
}

enter image description here


Solution

  • The file you're looking for should be in the same folder of the executable.

    If you're running your code from Qtcreator, it should be in the build directory, as specified in the Build Settings of the Projects page.