user285594
user285594

Reputation:

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

Upvotes: 1

Views: 175

Answers (2)

SGaist
SGaist

Reputation: 928

You should consider using QStandardPaths to query for a writable location for the screenshot to be saved to. This will avoid the issue of trying to write to a read-only directory.

Upvotes: 0

p-a-o-l-o
p-a-o-l-o

Reputation: 10047

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.

Upvotes: 1

Related Questions