Qt控制台输入输出实现exe间通信

包含

#include


输出到控制台

    QString str = tr("Im cld");
    QTextStream out(stdout);
    out << str < 中文支持 
  

QString str = QString::fromLocal8Bit("清输入任意参数:");


获取控制台的输入内容

    QTextStream in(stdin);
    if(!in.atEnd())
        in >> str;
    ui->textEdit->append(tr("接收到的参数")+str);


使用消息监听控制台的输入

    filein.open(stdin, QIODevice::ReadOnly);
    QSocketNotifier* sn = new QSocketNotifier(filein.handle(), QSocketNotifier::Read, this);
    connect(sn, SIGNAL(activated(int)), this, SLOT(readFromServer(int)));

实际测试没有接收到消息怀疑是QFile不支持readyRead



调用端实现

    myChildProcess = new QProcess(this);
    QObject::connect(myChildProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(receiver()));
 
  

//接收外部传入的参数
void MainWindow::receiver()
{
    QString str=tr("接收内容: ");
    ui->textEdit->append(str+myChildProcess->readAll());
}

//向外部程序发送参数
void MainWindow::on_pushButton_2_clicked()
{
    if(!myChildProcess->waitForStarted()){  //没有运行的子程序,向父窗口发送
        QTextStream out(stdout);
        out << ui->lineEdit_2->text() < 
  
        return;
    }
    QString str = ui->lineEdit_2->text()+tr("\r\n");
    myChildProcess->write(str.toLatin1().constData(),str.length());
    ui->textEdit->append(tr("内容发送"));
}

//调用外部程序
void MainWindow::on_pushButton_clicked()
{
    myChildProcess->setProcessChannelMode(QProcess::MergedChannels);
    myChildProcess->start(ui->lineEdit->text());
    if(!myChildProcess->waitForStarted()){
        ui->textEdit->append(tr("启动失败:%1").arg(myChildProcess->errorString()));
    }
    else{
        ui->textEdit->append("启动成功:请发送参数测试");
    }
}
 
  

你可能感兴趣的:(应用——Qt)