本篇博客参考链接
QProcess类的使用
- 新建一个类对应一个界面,该界面将调用外部程序
- 代码
Caesar.h
#ifndef CAESAR_H
#define CAESAR_H
#include <QProcess>
#include <QWidget>
namespace Ui {
class Caesar;
}
class Caesar : public QWidget
{
Q_OBJECT
public:
explicit Caesar(QWidget *parent = nullptr);
~Caesar();
private:
Ui::Caesar *ui;
QProcess *process;
QString out;
private slots:
void readOutput();//从进程中读取数据
void on_encrption_button_clicked();//点击按钮触发外部程序
};
#endif // CAESAR_H
Caesar.cpp
#include "caesar.h"
#include "ui_caesar.h"
#include <QDebug>
Caesar::Caesar(QWidget *parent) :
QWidget(parent),
ui(new Ui::Caesar)
{
ui->setupUi(this);
this->process = new QProcess;
QObject::connect(process,SIGNAL(readyRead()),this,SLOT(readOutput()));
//准备从进程里读数据的槽
}
Caesar::~Caesar()
{
delete ui;
}
void Caesar::on_encrption_button_clicked()
{
QString cmd = this->ui->keyword_line->text();//获取keyword_line的内容
QString plaintext=this->ui->plaintext_edit->toPlainText();
cmd = "./caesar.py e "+plaintext+" "+cmd;
qDebug()<<cmd; //相当于在终端执行命令 ./caesar e hello 5
//即在终端执行cmd字符串的内容
process->start(cmd);
out=tr("");
ui->ciphertext_edit->setText(out);
}
void Caesar::readOutput(){
out += process->readAll();
qDebug()<<out;
ui->ciphertext_edit->setText(out);
}
注:可执行文件一定要放在Qt项目对应的built文件中!!!