问:当QProcess将一行写入stdout时,有没有办法发送信号

时间:2011-06-08 13:08:36

标签: qt qt4

我发现了类似的问题,但从未找到确切的答案。我有Qt程序启动QProcess并将输出写入QTextEdit框,到目前为止一切顺利。但只有在程序结束时才会这样做。如果可能的话,我希望程序stdout能够在真实的时间打印出来。在一个理想的世界中,当有一条线路准备好读取时,QProcess会发出某种信号,如果QProcess不可能,那么它是否可能?理想情况下,在进程运行时,您仍然可以使用程序的其余部分。

这是我到目前为止的一些代码,非常简单,它只是将QProcess标准输出的第一行发送到QTextEdit

...
extProcess::extProcess(QObject *parent) :
    QObject(parent)
    extProcess::extProcess(QObject *parent) :
    QObject(parent)
{
    proc = new QProcess(this); //initialize proc
    arguments << "-v";
    connect(proc, SIGNAL(readyRead()), this, SLOT(logReady()));

}

void extProcess::startProcess()
{
    emit clearLog();
    emit outLog("--Process started--");
    proc->start("/Users/jonathan/Desktop/testgg");
}

void extProcess::logReady()
{
       emit outLog(proc->readLine());
}
...

这是我尝试的替代版本,这将显示整个QProcess输出但仍然     只在程序结束时显示它。

    ...
    extProcess::extProcess(QObject *parent) :
    QObject(parent)

{
    proc = new QProcess(this); //initialize proc
    proc->setProcessChannelMode(QProcess::SeparateChannels);
    arguments << "-v";
    connect(proc, SIGNAL(readyReadStandardOutput()), this, SLOT(logReady()));

}


void extProcess::logReady()
{

       while(proc->bytesAvailable()){
               emit outLog(proc->readLine());
       }
}



void extProcess::startProcess()
{
    emit clearLog();
    emit outLog("--Process started--");
    proc->start("/Users/jonathan/Desktop/testgg");
}



void extProcess::killProcess()
{
    proc->terminate();
    emit clearLog();
    emit outLog("--Process Terminated--");
}
....

由于

3 个答案:

答案 0 :(得分:6)

我使用readAllStandardOutput()来达到这个目的,这对我有用。

但是我确实注意到它不会收到任何标准输出,直到该进程实际刷新其输出缓冲区(“\ n”可能不会自动执行此操作,至少不是在我的完全平台特定的Windows体验中)。

根据子进程如何编写其输出(C应用程序或C ++应用程序),它需要分别调用fflush(stdout);或结束行std::endl;

答案 1 :(得分:3)

readLine()可能会等到第一个'\ n'字符被读取。

另一方面,

readAllStandardOutput返回流程标准输出中的所有可用数据。

所以在我看来,如果你使用readAllStandardOutput(),你可能会获得更多的性能。

你必须尝试。

答案 2 :(得分:2)

  

在一个理想的世界中,当有一条线准备好读取时,QProcess会发出某种信号

Qprocess信号readyReadStandardOutput()不完全符合您的要求吗?

您可以连接到它,然后您的广告位获取可用数据bytesAvailable()并查找'/n'个字符。或者只是readLine()canReadLine()

不要忘记开始您的过程,不要等待它完成。另外,设置ProcessChannelModeSeparateChannels

修改

我有一个类读取QProcess这样的行:

bool extProcess::logReady()
{
    while( proc->canReadLine())
    {
        QByteArray line = proc->readLine();
        /*do some with the line like copying it's content to a QTextEdit*/
    }
}

它运作良好。 我不确定emit outLog()信号!您是否尝试通过信号传递QByteArrayQByteArray中包含的数据必须保存在缓冲区中,您应该将指向此数组的指针传递给与其连接的任何人......

但是,如果您不想使用额外的内存并处理“消耗的数据是什么?......”,请执行您需要对logReady()方法中的数据执行的操作。