QProcess无法读取来自单独线程的输入

时间:2019-04-30 15:28:12

标签: c++ multithreading qprocess

我正在尝试使用QProcess从连续输出内容的线程中读取。我编写了这两个程序进行测试。虽然QProcess可以拾取主线程的输出(“ Counting ...”),但没有拾取输出。当我将while循环更改为for循环时,有一个输出,但是仅在程序完成执行之后。是否可以使用QProcess从单独的线程读取实时输出?

Qt代码:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    process = new QProcess(this);
    connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput()));
    //connect(process, SIGNAL(readyReadStandardError()),this,SLOT(readOutput()));
    process->setArguments(args);
    process->setProgram("C:\\Users\\chten\\OneDrive\\Desktop\\QProcess\\test\\Debug\\test.exe");
    process->start();
    process->waitForStarted();
}

MainWindow::~MainWindow()
{
    process->close();
    delete ui;
}

void MainWindow::readOutput() {
    ui->input->append(process->readAllStandardOutput());
}

C ++代码:

#include "pch.h"
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <iostream>
#include <string>

using namespace std;

void counting() {
    for(int i = 0; i < 10; i++){
        i++;
        std::cout << i << "\n";
        boost::this_thread::sleep_for(boost::chrono::seconds{ 1 });
    }
}

int main(int  argc, char *argv[])
{
    cout << "Counting..." << endl;
    boost::thread t{ counting };
    t.join();
    return 0;
}

0 个答案:

没有答案