我正在尝试捕获子QProcess的文本输出和输入,现在我需要在每当使用子系统(“ cls”)时得到通知,以便清除QTextEdit以显示和获取子输出。
editProcess.h
#ifndef EDITPROCESS_H
#define EDITPROCESS_H
#include <QPointer>
#include <QProcess>
#include <memory>
class QPlainTextEdit;
// a Process with plainTextEdit as output and input window
class EditProcess : public QProcess {
Q_OBJECT
public:
explicit EditProcess(QWidget *parent = nullptr);
QPointer<QPlainTextEdit> edit() { return m_textEdit; }
~EditProcess();
signals:
public slots:
private:
QPointer<QPlainTextEdit> m_textEdit;
protected:
bool eventFilter(QObject *, QEvent *event) override;
};
#endif // EDITPROCESS_H
editProcess.cpp
#include "editprocess.h"
#include <QDebug>
#include <QKeyEvent>
#include <QPlainTextEdit>
EditProcess::EditProcess(QWidget *parent)
: QProcess(parent), m_textEdit{new QPlainTextEdit}
// zm_textEdit(std::make_shared<QPlainTextEdit>(parent))
{
QObject::connect(this, &EditProcess::readyReadStandardOutput, [this]() {
m_textEdit->insertPlainText(readAllStandardOutput());
});
QObject::connect(this, &EditProcess::readyReadStandardError, [this]() {
m_textEdit->insertPlainText(readAllStandardError());
});
QObject::connect(
this,
static_cast<void (EditProcess::*)(int, QProcess::ExitStatus)>(
&EditProcess::finished),
[this](int exitCode, QProcess::ExitStatus) -> void {
m_textEdit->insertPlainText(readAllStandardOutput());
m_textEdit->insertPlainText(
QString("\nProgram Finished with exit code: %1").arg(exitCode));
});
m_textEdit->installEventFilter(this);
}
EditProcess::~EditProcess() { kill(); }
bool EditProcess::eventFilter(QObject *, QEvent *event) {
if (event->type() == QEvent::KeyPress) {
auto keyEvent = dynamic_cast<QKeyEvent *>(event);
if (keyEvent->modifiers() == Qt::CTRL && keyEvent->key() == Qt::Key_C)
kill();
else
write(keyEvent->text().toUtf8());
}
return false;
}
mainwidow.cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
auto p = new EditProcess(parent);
p->edit()->setParent(centralWidget());
p->setProgram(
"test.exe");
p->start();
qDebug() << p->errorString();
}
如果我现在从子进程中调用system("cls")
,则什么也没发生,QTextEdit保持不变,我没有发现任何变化