Pregunta

Suppose I run a console application using QProcess. The application runs, displays some information, and then waits for n seconds and displays other information.

My current code is:

QProcess * p = new QProcess();
p->start("test.bat");
p->waitForStarted();
p->waitForFinished();
p->readAll();
delete p;

Currently I get all the output at the end, but what I need to do is get the output and display it as it becomes available. How do I do this?

¿Fue útil?

Solución

You could connect to the readyRead() signal, so whenever there is some data to read, you will keep reading it and display without waiting for the process to finish. That means the following in terms of code:

class Foo : public QObject
{
    Q_OBJECT
public:
    explicit Foo::Foo(QObject parent = Q_NULLPTR)
        : QObject(parent)
    {
        ...
        connect(myProcess, SIGNAL(readyRead()), SLOT(handleReadyRead()));
        connect(myProcess, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(handleFinished(int, QProcess::ExitStatus)));
        connect(myProcess, SIGNAL(error(QProcess::ProcessError)), SLOT(handleError(QProcess::ProcessError)));
        myProcess.start("test.bat");
        ...
    }

public slots:
    void Foo::handleReadyRead()
    {
        qDebug() << myProcess.readAll();        
    }

    void Foo::handleFinished(int, QProcess::ExitStatus)
    {
        // Handle finished        
    }

    void Foo::handleError(QProcess::ProcessError)
    {
        // Handle error
    }

private:
    QProcess myProcess;
}

Disclaimer: consider it as pseudo-code as I have not built it, but it should demonstrate the concept to use.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top