如何在 Qt 应用程序中通过终端命令 运行 分离应用程序?

How to run a detached application by terminal command in Qt application?

我想使用命令:

cd /opencv/opencv-3.0.0-alpha/samples/cpp/
./cpp-example-facedetect lena.jpg

至运行 Qt应用程序中按钮的clicked()方法的OpenCV示例代码。 所以我使用:

void MainWindow::on_btSample_clicked()
{
        QProcess process1;
        QProcess process2;

        process1.setStandardOutputProcess(&process2);

        process1.start("cd /opencv/opencv-3.0.0-alpha/samples/cpp");
        process1.waitForBytesWritten();
        process2.start("./cpp-example-facedetect lena.jpg"); 
}

我添加了必要的库来使用它。但是当我 运行 我的应用程序时出现错误。

QProcess: Destroyed while process ("./cpp-example-facedetect") is still running.

我该如何解决?如果我做的方式不对,请给我另一种方式。提前谢谢你!

我认为你有两个问题:

首先,您的 QProcess process2 可能在完成之前超出范围(即由于超出范围而被销毁)。您要么必须等待它完成(使用 waitForFinished(),要么使它成为指针或成员变量(以更改范围)并将 finished() 信号连接到某个处理槽(它可以做整洁向上)。

这里的另一件事是,看起来您只想设置工作目录,所以我不认为将 cd 命令通过管道传输到您的可执行文件中是可行的方法,这样做会更容易:

编辑

我已经编辑了示例以向您展示如何获得输出:

QProcess myProc;

qDebug() << "Starting process\n";
// Setup the working directory
QDir::setCurrent("D:\software\qtTest");

// Start the process (uses new working dir)
myProc.start("test.bat");

myProc.waitForFinished();
qDebug() << myProc.readAll();

我用了大约 2 分钟就把它放在我的 windows 盒子上并为你测试了...我可以在 linux 上做,但这需要我更长的时间,因为我有启动它 :o ... 但如果你愿意,我会的。

编辑 2

如果您想完全分离进程:

QProcess myProc;

qDebug() << "Starting process\n";
// Setup the working directory
QDir::setCurrent("D:\software\qtTest");

// Start the process (uses new working dir)
myProc.startDetached("test.bat");

现在我不能 100% 确定您可以从过程中取回输出...现在它与您的 Qt 应用程序无关...