1

fairly new to Qt.

I'm using QProcess to run an external shell script and redirecting the output to a textBrowser on my GUI. Code:

In mainwindow.h:

private:
   QProcess *myProcess;

and mainwindow.cpp:

void MainWindow::onButtonPressed(){
   myProcess = new QProcess(this);
   myProcess->connect(myProcess, SIGNAL(readyRead()), this, SLOT(textAppend()));
   myProcess->start("./someScript.sh", arguments);
}

void MainWindow::textAppend(){
   ui->textBrowser->append(myProcess->readAll());
}

This works perfectly to run an external script. My question is how to apply the same process with the script included as a resource file. I've tried simply replacing "./someScript.sh" with the resource version ":/someScript.sh" but it does not seem to work. The resource script runs perfectly, but the console output disappears.

4

2 回答 2

5

出于这个原因,有一个叫做“ QTemporaryFile ”类的东西。

因为您需要调用系统中已经存在的文件- 好的!

让我们举个例子:

使用QProcess我们需要从资源中运行一个 python 文件

//[1] Get Python File From Resource
QFile RsFile(":/send.py");
//[2] Create a Temporary File
QTemporaryFile *NewTempFile = QTemporaryFile::createNativeFile(RsFile);
//[3] Get The Path of Temporary File
QStringList arg;
arg << NewTempFile->fileName();
//[4] Call Process
QProcess *myProcess = new QProcess(this);
myProcess->start("python", arg);
//[5] When You Finish, remove the temporary file
NewTempFile->remove();

注意:在 Windows 上,临时文件存储在%TEMP%目录中

有关更多信息,您可以访问Qt 文档 - QTemporaryFile 类

祝你好运♥</p>

于 2017-10-01T02:33:53.527 回答
1

我不工作,因为当您运行时,myProcess->start(":/someScript.sh", arguments);您要求您的系统运行您的系统:/someScript.sh不存在。

一个快速的解决方案是将脚本复制到一个临时文件夹并从那里运行它。

QFile::copy(":/someScript.sh", pathToTmpFile);
myProcess->start(pathToTmpFile, arguments);

我还建议您使用QTemporaryFile获取唯一的临时文件名。

于 2016-12-21T10:24:24.650 回答