动态库中的Spawn Async QProcess,Peek输出直到完成

时间:2015-09-15 18:51:04

标签: c++ qt asynchronous qprocess

在Qt / C ++中,从动态库(Qt C ++类项目),我需要为命令行命令生成一个新进程(dir /s是一个很好的例子),而不需要锁定调用它的GUI库函数。然后,我需要查看此标准输出和标准错误,直到生成的进程完成。如何从动态库中生成异步QProcess,然后查看输出直到它完成?

以下代码不起作用,但它有一些显示思考过程的部分。

QString ctCommand::testCommand()
{
  QObject *parent;
  QProcess *console = new QProcess(parent);
  console->connect(console,SIGNAL(readyReadStandardOutput()),this,SLOT(out()));
  console->setReadChannel(QProcess::StandardOutput);
  console->start("dir /s");
}

QString ctCommand::out()
{
  QByteArray processOutput;
  processOutput = console->readAllStandardOutput();
  return QString(processOutput);
}

1 个答案:

答案 0 :(得分:3)

您需要将从库启动的对象的信号连接到主类对象。

<强>

<强> process.h

#include <QtCore/qglobal.h>
#include <QObject>
#include <QProcess>

#if defined(PROCESS_LIBRARY)
#  define PROCESSSHARED_EXPORT Q_DECL_EXPORT
#else
#  define PROCESSSHARED_EXPORT Q_DECL_IMPORT
#endif

class PROCESSSHARED_EXPORT Process : public QObject
{
     Q_OBJECT
public:
    Process(const QString &p_Command, QObject *p_Parent = nullptr);
    QString getCommand() const;

signals:
    void readyRead(QByteArray);

public slots:
    void runCommand(const QString &p_Command);
    void runCommand();
    void setCommand(const QString &p_Command);

private slots:
    void out();
    void processFinished(int p_Code);

private:
    QString command;
};

<强> process.cpp

#include "process.h"

Process::Process(const QString &p_Command, QObject *p_Parent)
    : QObject(p_Parent)
{
    command = p_Command;
}

void Process::runCommand(const QString &p_Command) {
    command = p_Command;
    runCommand();
}

void Process::runCommand() {
    QProcess *console = new QProcess(this);
    console->connect(console, SIGNAL(readyRead()),
        this, SLOT(out()));
    console->connect(console, SIGNAL(finished(int)),
        this, SLOT(processFinished(int)));
    console->start(command);
}

void Process::out() {
    QProcess *console = qobject_cast<QProcess*>(QObject::sender());
    QByteArray processOutput = console->readAll();
    emit readyRead(processOutput);
}

void Process::processFinished(int p_Code) {
    QProcess *console = qobject_cast<QProcess*>(QObject::sender());
    QByteArray processOutput = console->readAll()
        + QString("Finished with code %1").arg(p_Code).toLatin1();
    emit readyRead(processOutput);
}

QString Process::getCommand() const {
    return command;
}

void Process::setCommand(const QString &p_Command) {
    command = p_Command;
}

<强> 用法

void MainWindow::showCustomMessage()
{
    Process *tempProcess = new Process("ping google.com", this);
    connect(tempProcess, SIGNAL(readyRead(QByteArray)),
        this, SLOT(processResponded(QByteArray)));
    tempProcess->runCommand();
}

void MainWindow::processResponded(QByteArray p_Data) {
    qDebug() << p_Data;
}

如果有人对在Qt中创建图书馆有疑问 - 请访问官方Wiki