本文通过QProcess,实现了在Qt中调用外部程序(控制台程序),并将输出重定向到了一个QTextEdit里。效果如下图所示:
运行界面如下:
程序共包含以下三个文件:
-
- #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();
- }
//: 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();
}
-
- #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.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
-
- #include
- #include "process.h"
- Process::Process(QWidget *parent, Qt::WFlags flags)
- : 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);
- }