Reputation: 40
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.
I'd like to create a field within the GUI and display the output of the script. 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.
Would using QProcess
be a better approach?
If so, how would I get started?
Also, what Qt Widget/container would you recommend?
Upvotes: 0
Views: 1104
Reputation: 5466
Would using QProcess be a better approach? If so, how would I get started?
By looking at the QProcess documentation, you can do something similar to this:
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)
.
Executing shell scripts with QProcess
should work fine, as long as they are marked with #! interpreter [optional-arg]
at the beginning. This is because QProcess
internally uses fork
+ execvp
, and the documentation for that clearly states shell scripts are allowed.
Don't forget to delete your QProcess
when the command has finished.
Also, what Qt Widget/container would you reccomend?
Sounds like a job for QPlainTextEdit. Alternatively, you can use the slower QTextEdit, which brings additional features.
Upvotes: 8