我有一个脚本,它在控制台上以“1秒”的间隔回响“Hello world”5次。当我在Qt中使用相同的脚本时,行为是不一样的。
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());
如果我不使用“process-&gt; waitForFinished()”,应用程序不会在textBrowser中显示任何输出,但是如果使用相同的块调用,我可以在控制台上看到o / p但问题是它没有动态。它应该打印“Helloworld”睡眠1秒并再次遵循相同的行为。 但是使用这段代码我最终得到了控制台上的o / p,所有的“Helloworld”打印都不是一个接一个。
我应该研究什么?
答案 0 :(得分:0)
Hy Learner,
您可以使用QProcess::readyReadStandardOutput()
信号捕获每个实时输出:
// 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");
注意:代码未经测试!