0

I have a script which echos "Hello world" 5 times on the console with an interval on 1 sec. When i use the same script in Qt, the behavior is not the same.

QProcess *process = new QProcess;
//Step1 - create a new process
process->start("/bin/sh", QStringList()<< "pathtoscript.sh");
process->waitForFinished();

// Step2 - display the script output on text browser
ui->textBrowser->setText(process->readAllStandardOutput());

If I don't use "process->waitForFinished()", the application doesn't show any output in textBrowser, howsover using the same block call, I can see the o/p on console but the problem is its not dynamic. It should print "Helloworld" sleep for 1 sec and again follow the same behavior. But with this code i get the o/p on console in the end, All the "Helloworld" prints togather not one by one.

What should I look into?

demonplus
  • 5,613
  • 12
  • 49
  • 68
Learner
  • 67
  • 7
  • Possible duplicate of [Running c++ binary from inside Qt and redirecting the output of the binary to a textbox on the Qt Application](https://stackoverflow.com/questions/14960472/running-c-binary-from-inside-qt-and-redirecting-the-output-of-the-binary-to-a) – eyllanesc Jul 24 '17 at 05:38

1 Answers1

0

Hy Learner,

you could use the QProcess::readyReadStandardOutput() signal to capture every live output:

// example QObject class for capturing QProcess' stdout
// the slot_readyReadStandardOutput() can also be implemented
// in your QApplication or any other QObject implementation
class QProcessOutputCapturer : public QObject
{
    Q_OBJECT
    public:
        QProcessOutputCapturerer(QProcess* pProcess, QTextBrowser* pTextBrowser)
          : QObject(pProcess),
            m_pTextBrowser(pTextBrowser) 
        {
            connect(pProcess, SIGNAL(readyReadStandardOutput()), pTextBrowser, SLOT(slot_readyReadStandardOutput()));
        }

    public slot:
        // this is called whenever the QProcess::readyReadStandardOutput() signal is fired
        void slot_readyReadStandardOutput() {
            QProcess* pProcess = qobject_cast<QProcess*>(sender());
            if (pProcess) {
                m_pTextBrowser->append(pProcess->readAllStandardOutput());
            }
        }

    protected:
        QTextBrowser* m_pTextBrowser;
};

QProcess *process = new QProcess;
QProcessOutputCapturer capturer(process, ui->textBrowser);

// start process
process->start("/bin/sh", QStringList()<< "pathtoscript.sh");

Note: Code is untested!