Qt QProcess有时能用有时不能用

Qt QProcess sometimes works and sometimes does not work

我想通过 ps2pdfps 文件转换为 pdf,Qt 中的代码如下:

QPixmap graphPng(filePath +  "report/pictures/graph-000.png");
int graphPsWidth=graphPng.width();
int graphPsHeight=graphPng.height();

//convert "ps" file to "pdf" file
QProcess process;
QStringList arg;
arg<<"-dDEVICEWIDTHPOINTS=" + QString::number(graphPsWidth)<<"-dDEVICEHEIGHTPOINTS=" + QString::number(graphPsHeight)<<"export/report/pictures/graph-000.ps"<<"export/report/pictures/graph-000.pdf";
process.start("ps2pdf",arg);
//process.waitForStarted(-1);
process.waitForFinished(-1);

(我使用与 ps 文件相同尺寸的 png 文件来获取尺寸并将其用于创建 pdf 文件)

我不知道为什么有时会创建 pdf 文件,有时却没有任何输出消息(process::readAllStandardError()process::readAllStandardOutput())没有 pdf 文件!

pdf 文件未创建时,如果我 运行 立即在终端中创建 pdf 文件!!!

是什么原因,如何解决?

验证所有步骤总是明智的,所以我分享了一个更健壮的代码版本。

例如不一定要用QPixmap,正确的是用QImage。此外,文件的路径已验证。

#include <QCoreApplication>
#include <QDir>
#include <QProcess>
#include <QImage>

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

    QDir directory(QString("%1%2%3")
                   .arg(a.applicationDirPath())
                   .arg(QDir::separator())
                   .arg("export/report/pictures/"));

    QString name = "graph-000";
    QString png_path = directory.filePath(name + ".png");
    QString ps_path = directory.filePath(name + ".ps");

    // verify path
    Q_ASSERT(QFileInfo(png_path).exists());
    Q_ASSERT(QFileInfo(ps_path).exists());

    QString pdf_path = directory.filePath(name+".pdf");

    QImage img(png_path);
    int graphPsWidth = img.width();
    int graphPsHeight = img.height();

    QProcess process;
    QStringList arg;
    arg << QString("-dDEVICEWIDTHPOINTS=%1").arg(graphPsWidth) <<
         QString("-dDEVICEHEIGHTPOINTS=%1").arg(graphPsHeight) <<
         ps_path << pdf_path;

    process.start("ps2pdf",arg);
    process.waitForFinished();
    Q_ASSERT(QFileInfo(pdf_path).exists());
    return 0;
}

我可以通过处理 RAM 来解决问题,因为如果 ram 超过特定限制(几乎接近 RAM 的全部容量),QProcess 将无法启动。因此,每次它诊断出超出限制时,都不会创建 PDF 文件,反之亦然。