在 textBrowser 中实时显示 QProcess 输出 [英] Real time display of QProcess output in a textBrowser

查看:99
本文介绍了在 textBrowser 中实时显示 QProcess 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 qt 开发的新手,我想将 QProcess 的输出实时传输到 textBrowser.我首先执行一个简单的 echo 命令,但没有显示程序的输出.我做错了什么????

I am a newbie in qt development and i want to transfer the output of QProcess to a textBrowser in real time. I started by executing a simple echo command,but the output of the program is not getting displayed. What am i doing wrong????

QProcess p;
p.start("echo hye");
QByteArray byteArray = p.readAllStandardOutput();
    QStringList strLines = QString(byteArray).split("\n");
    QString line= p.readAllStandardOutput();
    if(p.state()==QProcess::NotRunning)
        ui->textBrowser->append("not running");
    foreach (QString line, strLines){
    ui->textBrowser->append(line);}

附言我在一台 linux 机器上.

P.S. I am on a linux machine.

我仍然无法在 textBrowser 中获得输出.

I am still not able to get the output in a textBrowser .

我更改了 Qprocess 参数并尝试了 waitForStarted() 和 waitForReadyRead() 以便进程及时启动并且结果可用.

I changed the Qprocess parameters and tried both waitForStarted() and waitForReadyRead() so that the process starts in time and the results are available.

我添加了 waitForFinished() 以便进程在超出范围时不会终止.

I added waitForFinished() so that the process does not terminate when it goes out of scope.

QProcess p;
    p.start("echo", QStringList() << "hye");
    p.waitForStarted();
    QByteArray byteArray = p.readAllStandardOutput();
    QStringList strLines = QString(byteArray).split("\n");
    QString line= p.readAllStandardOutput();
    if(p.state()==QProcess::NotRunning)
        ui->textBrowser->append("not running");
    ui->textBrowser->append(line);
    p.waitForFinished();

推荐答案

要读取标准输出,您需要在读取标准输出之前调用 waitForReadyRead() ,或者您需要连接 Qprocess 的信号 readyReadStandardOutput() 到您的插槽并从插槽读取标准输出.

to read standard output you need to either call waitForReadyRead() before reading stardard output , or you need to connect Qprocess's signal readyReadStandardOutput() to your slot and read standard output from slot.

还要确保您的 QProcess 不在堆栈中.

also make sure that your QProcess is not on stack.

我尝试以下代码工作正常.

I tried following code works fine.

MyProcess::MyProcess(QObject *parent) :
    QObject(parent)
{
    QString program = "echo";
    QStringList arguments;
    arguments << "Hello";
    mProcess.start(program,arguments);
    connect(&mProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(readyReadStandardOutput()));
    connect(&mProcess,SIGNAL(readyReadStandardError()),this,SLOT(readyReadStandardError()));
}

void MyProcess::readyReadStandardOutput(){
    qDebug()<< mProcess.readAllStandardOutput();
}

void MyProcess::readyReadStandardError(){
    qDebug() << mProcess.readAllStandardError();
}

这篇关于在 textBrowser 中实时显示 QProcess 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆