[英]How can I capture terminal output from a bash script and display it in my Qt UI?
I've written a simple GUI that guides the user through a checkout/checkin procedure, and then runs a bash script when the user clicks a GUI button. 我编写了一个简单的GUI,该向导可以指导用户完成检出/检入过程,然后在用户单击GUI按钮时运行bash脚本。
I'd like to create a field within the GUI and display the output of the script. 我想在GUI中创建一个字段并显示脚本的输出。 Right now I'm using
system()
(stdio) to run the script, but piping the script's output to a text field in my gui seems messy. 现在,我正在使用
system()
(stdio)运行脚本,但是将脚本的输出传递到gui中的文本字段中似乎很麻烦。
Would using QProcess
be a better approach? 使用
QProcess
会是更好的方法吗? If so, how would I get started? 如果是这样,我将如何开始?
Also, what Qt Widget/container would you recommend? 另外,您会推荐什么Qt Widget /容器?
Would using QProcess be a better approach?
使用QProcess会是更好的方法吗? If so, how would I get started?
如果是这样,我将如何开始?
By looking at the QProcess documentation , you can do something similar to this: 通过查看QProcess文档 ,您可以执行以下操作:
QString program = "/usr/bin/ls";
QStringList arguments{"-lahR"};
QProcess *myProcess = new QProcess(parent);
myProcess->start(program, arguments);
connect(myProcess, &QProcess::readyReadStandardOutput, [myProcess] {
qDebug() << "Got output from process:" << myProcess->readAllStandardOutput();
// Or copy the data to QPlainTextEdit::appendPlainText()
});
You probably also want to capture standard error output. 您可能还希望捕获标准错误输出。 You can either do a second
connect()
or use QProcess::setProcessChannelMode(QProcess::MergedChannels)
. 您可以执行第二个
connect()
或使用QProcess::setProcessChannelMode(QProcess::MergedChannels)
。
Executing shell scripts with QProcess
should work fine, as long as they are marked with #! interpreter [optional-arg]
只要用
#! interpreter [optional-arg]
标记,用QProcess
执行shell脚本就可以正常工作#! interpreter [optional-arg]
#! interpreter [optional-arg]
at the beginning. 开头的
#! interpreter [optional-arg]
。 This is because QProcess
internally uses fork
+ execvp
, and the documentation for that clearly states shell scripts are allowed. 这是因为
QProcess
内部使用fork
+ execvp
,并且该文档明确指出允许使用shell脚本。
Don't forget to delete your QProcess
when the command has finished. 命令完成后,请不要忘记删除您的
QProcess
。
Also, what Qt Widget/container would you reccomend?
另外,您会推荐哪种Qt Widget /容器?
Sounds like a job for QPlainTextEdit . 听起来像QPlainTextEdit的工作。 Alternatively, you can use the slower QTextEdit , which brings additional features.
另外,您可以使用速度较慢的QTextEdit ,它带来了附加功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.