Mactarvish
Mactarvish

Reputation: 45

How to execute a python console using Qt on win10?

I'm trying to execute a python console using QProcess and show the content of the console in a QTextEdit. Below is my major codes:

    connect(&process, SIGNAL(readyReadStandardOutput()), this, SLOT(PrintStandardOutput()));
    connect(&process, SIGNAL(started()), this, SLOT(Started()));
    ...
    void Widget::PrintStandardOutput()
    {
        QString stdOtuput = QString::fromLocal8Bit(process.readAllStandardOutput());
        ui->textEdit_Output->append(stdOtuput);
    }

    void Widget::Started()
    {
        ui->stateLabel->setText("Process started...");
    }


I used QProcess::start("python") to start a new process and QProcess::write() to write my python codes, but I can see nothing shown in my QTextEdit, by the way, the python process is indeed executed according to the stateLabel showning "Process started...". How to let the python output shown in the QTextEdit? Thanks.

Upvotes: 0

Views: 127

Answers (1)

user6223604
user6223604

Reputation:

Try :

        connect(&process, SIGNAL(readyReadStandardOutput()), this, SLOT(PrintStandardOutput()));

        connect(&process, SIGNAL(started()), this, SLOT(Started()));

        process.setProcessChannelMode(QProcess::MergedChannels);
        process.start(processToStart, arguments)

        void Widget::PrintStandardOutput()
        {

            // Get the output
            QString output;
            if (process.waitForStarted(-1)) {
                while(process.waitForReadyRead(-1)) {
                    output += process.readAll();
                    ui->textEdit_Output->append(output);
                }
            }
            process.waitForFinished();
        }

        void Widget::Started()
        {
        ui->stateLabel->setText("Process started...");
        }

setProcessChannelMode(QProcess::MergedChannels) will merge the output channels. Various programs write to different outputs. Some use the error output for their normal logging, some use the "standard" output, some both. Better to merge them.

readAll() reads everything available so far.

It is put in a loop with waitForReadyRead(-1) (-1 means no timeout), which will block until something is available to read. This is to make sure that everything is actually read. Simply calling readAll() after the process is finished has turned out to be highly unreliable (buffer might already be empty).

Upvotes: 1

Related Questions