Qtの基礎 - プロセス

提供:MochiuWiki : SUSE, EC, PCB
2021年2月13日 (土) 20:23時点におけるWiki (トーク | 投稿記録)による版 (ページの作成:「== 概要 == Qtにおいて、<code>QProcess</code>クラスを使用して、プロセスを制御する手順を記載する。<br> <br><br> == サンプルコード =…」)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

概要

Qtにおいて、QProcessクラスを使用して、プロセスを制御する手順を記載する。


サンプルコード

プロセスを非同期で実行する場合はQProcess::start()、同期して実行する場合はQProcess.execute()を使用する。
また、非同期で実行する場合、標準出力や標準エラー出力を取得してウィンドウに表示することもできる。

以下の例は、プロセスを非同期で実行して、プロセスの標準出力と標準エラー出力をウィンドウに表示している。

 // MainWindow.h
 
 #ifndef MAINWINDOW_H
 #define MAINWINDOW_H
 
 #include <QMainWindow>
 #include <QProcess>
 
 QT_BEGIN_NAMESPACE
 namespace Ui { class MainWindow; }
 QT_END_NAMESPACE
 
 class MainWindow : public QMainWindow
 {
    Q_OBJECT
 
 private:
    QProcess m_proc;
  
 public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
 
 private slots:
    // プロセス用のスロット
    void proc_finished(int exitCode, QProcess::ExitStatus exitStatus);
    void updateOutput();
    void updateError();
 };
 #endif // MAINWINDOW_H


 // MainWindow.cpp
 
 #include <QApplication>
 #include <QProcess>
 #include "Mainwindow.h"
 #include "ui_Mainwindow.h"
 
 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
 {
    ui->setupUi(this);
 
    // コンストラクタあたりでシグナル−スロット接続
    QObject::connect(&m_proc, SIGNAL(readyReadStandardOutput()), this, SLOT(updateOutput()));
    QObject::connect(&m_proc, SIGNAL(readyReadStandardError()), this, SLOT(updateError()));
    QObject::connect(&m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(ProcessFinished(int, QProcess::ExitStatus)));
 }
 
 MainWindow::~MainWindow()
 {
    delete ui;
 }
 
 // スロット : 標準出力を表示する
 void MainWindow::updateOutput()
 {
    // 標準出力を取り出して文字列にする
    QByteArray output = m_proc.readAllStandardOutput();
    QString str = QString::fromLocal8Bit(output);
 }
 
 // スロット : 標準エラー出力を表示する
 void MainWindow::updateError()
 {
    // 標準エラー出力を取り出して文字列にする
    QByteArray output = m_proc.readAllStandardError();
    QString str = QString::fromLocal8Bit(output);
 }
 
 // スロット : プロセス終了時
 void MainWindow::ProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
 {
    if(exitStatus == QProcess::CrashExit)
    {
       QMessageBox::warning(this, tr("Error"), tr("Crashed"));
    }
    else if(exitCode != 0)
    {
       QMessageBox::warning(this, tr("Error"), tr("Failed"));
    }
    else
    {  // 正常終了時の処理
    }
 }
 
 // プロセスの起動
 void MainWindow::ProcessStart()
 {
    QStringList strlArgs;
    listArgs << "<引数1>" << "<引数2>";
 
    m_proc.start("<実行するプログラムのパス>", listArgs);
 }