0

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?

Drise
  • 4,310
  • 5
  • 41
  • 66
Mark
  • 40
  • 3

1 Answers1

8

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.

Drise
  • 4,310
  • 5
  • 41
  • 66
Thomas McGuire
  • 5,308
  • 26
  • 45
  • 1
    You mention that QProcess can not execute shell scripts directly -- I just tested this on Qt 5.5 and it worked without issue. Do your scripts have the `#!/bin/[ba]sh` shebang line? Are they marked executable? – Paul Belanger May 01 '18 at 17:07
  • Thannks for the reccomendation, I'm tinkering with this QProccess method now – Mark May 01 '18 at 18:23
  • @PaulB Oh indeed, you are right, shell scripts are allowed, I wasn't aware of that. Thanks for pointing that out. I've edited the answer to reflect that. – Thomas McGuire May 01 '18 at 18:58