gpt4 book ai didi

c++ - 从动态库生成异步 QProcess,查看输出直到完成

转载 作者:行者123 更新时间:2023-11-27 22:56:27 25 4
gpt4 key购买 nike

在 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);
}

最佳答案

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

图书馆

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;
};

进程.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

关于c++ - 从动态库生成异步 QProcess,查看输出直到完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32593463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com