程序共包含以下有一个文件:
//: main.cpp
#include "process.h"
#include
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
Process w;
w.show();
return a.exec();
}
//: process.h
#ifndef PROCESS_H
#define PROCESS_H
#include
class QLabel;
class QLineEdit;
class QProcess;
class QPushButton;
class QTextEdit;
class Process : public QWidget
{
Q_OBJECT
public:
Process(QWidget *parent = 0, Qt::WFlags flags = 0);
~Process();
private slots:
void runClicked();
void readOutput();
private:
QProcess* cmd;
QString output;
//用于保存输出结果
QLabel* inputLabel;
QLineEdit* inputEdit;
QPushButton* runButton;
QLabel* outputLabel;
QTextEdit* outputEdit;
};
#endif // PROCESS_H
//: process.cpp
#include
#include "process.h"
Process::Process(QWidget *parent, Qt::WFlags flags = 0)
: QWidget(parent, flags)
{
inputLabel = new QLabel(tr("请输入命令:"));
inputEdit = new QLineEdit;
runButton = new QPushButton(tr("运行"));
outputLabel = new QLabel(tr("运行结果如下:"));
outputEdit = new QTextEdit;
outputEdit->setReadOnly(true);
QHBoxLayout* hlayout = new QHBoxLayout;
hlayout->addWidget(inputEdit);
hlayout->addWidget(runButton);
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(inputLabel);
layout->addLayout(hlayout);
layout->addWidget(outputLabel);
layout->addWidget(outputEdit);
setLayout(layout);
cmd = new QProcess;
connect(inputEdit, SIGNAL(returnPressed()), this, SLOT(runClicked()));
connect(runButton, SIGNAL(clicked(bool)), this, SLOT(runClicked()));
connect(cmd, SIGNAL(readyRead()), this, SLOT(readOutput()));
resize(500, 300);
}
Process::~Process()
{
}
void Process::runClicked()
{
QString input = inputEdit->text();
//输入指令
cmd->start(input);
output = tr("");
outputEdit->setText(output);
}
void Process::readOutput()
{
output += cmd->readAll();
outputEdit->setText(output);
}