Qt QProcess应用

  本文通过QProcess,实现了在Qt中调用外部程序(控制台程序),并将输出重定向到了一个QTextEdit里。效果如下图所示:

运行界面如下:

Qt QProcess应用_第1张图片

 

//process.cpp
#include <QtGui>
#include "process.h"
Process::Process(QWidget *parent, Qt::WFlags flags):QWidget(parent, flags)
{
	inputLabel = new QLabel(tr("input command ?"));
	inputEdit = new QLineEdit;
	runButton = new QPushButton(tr("run"));
	outputLabel = new QLabel(tr("result"));
	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);
}


 

#ifndef PROCESS_H
#define PROCESS_H
#include <QWidget>
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


 

//main.cpp
#include "process.h"
#include <QApplication>
#include <QTextCodec>
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();
}


 

你可能感兴趣的:(command,layout,input,qt,Signal,output)