【问题标题】:Qt5 - why not screenshot and saving to a file?Qt5 - 为什么不截图并保存到文件?
【发布时间】:2017-12-03 10:52:34
【问题描述】:

为什么它不保存任何文件?

#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();
}

【问题讨论】:

  • 要区分代码问题和工作目录配置问题,请尝试硬编码绝对输出路径。
  • 因为 C:\ 可能需要管理员权限才能写入。尝试主目录中的路径,例如桌面
  • 现在可以通过添加 C:\\
  • 是的,您应该转义正斜杠。您可以在项目设置中设置工作目录(IDE 运行程序的目录)。为了在没有 IDE 的情况下运行程序,您需要将 Qt 的 bin/ 目录包含到您的 PATH 环境变量中,或者将所需的 .dll 文件从那里复制到程序的目录中。

标签: c++ windows qt qt5 qpixmap


【解决方案1】:

您要查找的文件应位于可执行文件的同一文件夹中。

如果您从 Qtcreator 运行代码,它应该位于构建目录中,如项目页面的构建设置中指定的那样。

【讨论】:

  • 请看我上面的编辑截图。它根本没有保存在那里。
  • 尝试直接执行(双击)untitled.exe,看看会发生什么。
【解决方案2】:

您应该考虑使用QStandardPaths 来查询要保存屏幕截图的可写位置。这将避免尝试写入只读目录的问题。

【讨论】:

    猜你喜欢
    • 2014-12-01
    • 2014-02-07
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 2011-09-22
    相关资源
    最近更新 更多