首页 > 代码库 > 【Qt】使用QProcess调用其它程序或脚本
【Qt】使用QProcess调用其它程序或脚本
大概试了一下,还是不错的,不过字符编码问题还不太好解决:
代码:
#include "mainwindow.h"#include "ui_mainwindow.h"#include <QMessageBox>#include <QProcess>#include <QTextCodec>#include <QCloseEvent>MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); QTextCodec::setCodecForLocale(QTextCodec::codecForName("KOI8-R")); ui->progressBar->setValue(0);}MainWindow::~MainWindow(){ delete ui;}void MainWindow::on_pushButton_clicked(){ process = new QProcess(this); QStringList str; str << ""; if (ui->pushButton->text() == "stop") { process->write("quit"); process->kill(); return; } QString exe = QApplication::applicationDirPath().append("/test.bat"); connect(process, SIGNAL(started()), this, SLOT(start_process())); connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(start_read_output())); connect(process, SIGNAL(readyReadStandardError()), this, SLOT(start_read_err_output())); connect(process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finish_process(int, QProcess::ExitStatus))); process->start(exe); if (false == process->waitForStarted()) { ui->textBrowser->append("this process can not be called."); } ui->pushButton->setText("stop");}void MainWindow::start_process(){ ui->progressBar->setVisible(true); ui->progressBar->setValue(0); //QMessageBox::information(this, "ok", "ok", QMessageBox::Ok); ui->textBrowser->append(tr("process start"));}void MainWindow::finish_process(int exitCode, QProcess::ExitStatus exitStatus){ if (exitStatus == QProcess::NormalExit) { ui->textBrowser->append(tr("process exit normal")); } else { ui->textBrowser->append(tr("process exit crash")); } ui->progressBar->setValue(100); ui->textBrowser->append("process finised"); ui->pushButton->setText("ok");}void MainWindow::start_read_output(){ QByteArray ba = process->readAllStandardOutput(); ui->textBrowser->append(ba);}void MainWindow::start_read_err_output(){ QByteArray ba = process->readAllStandardError(); ui->textBrowser->append("error: " + ba);}void MainWindow::closeEvent(QCloseEvent *event){ process->write("quit"); process->kill(); if(!process->waitForFinished(100)) return; event->accept();}
头文件:
#ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>#include <QProcess>namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{ Q_OBJECTpublic: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); QProcess* process;protected: void closeEvent(QCloseEvent *);private slots: void on_pushButton_clicked(); void start_process(); void start_read_output(); void start_read_err_output(); void finish_process(int exitCode, QProcess::ExitStatus exitStatus);private: Ui::MainWindow *ui;};#endif // MAINWINDOW_H
最后执行结果:
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。