한국어
Qt
 

응용 프로그램이 재시작하여 새로운 구성을 로드해야하는 경우가 종종 있다. 이럴 때 QProcess 클래스를 사용하여 응용 프로그램을 재시작하는 예제이다. 윈도우의 닫기 버튼을 누르면 앱은 그냥 종료되고 "재시작" 버튼을 누르면 종료 후 다시 실행된다.

qprocess.png

main.cpp

#include "mainwindow.h"

#include <QApplication>
#include <QProcess>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;
    w.show();

    int result = a.exec();

    if (EXIT_RESTART == result || EXIT_RESET == result) {
        qDebug() << "restarting app";
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
        ::qputenv("LIBGL_ALWAYS_SOFTWARE",
                  Settings.drawMethod() == Qt::AA_UseSoftwareOpenGL && !Settings.playerGPU()
                  ? "1" : "0");
#endif
        QProcess *restart = new QProcess;
        QStringList args = a.arguments();
        if (!args.isEmpty())
            args.removeFirst();
        restart->start(a.applicationFilePath(), args, QIODevice::NotOpen);
        result = EXIT_SUCCESS;
    }
    return result;
}

mainwindow.cpp

#include "mainwindow.h"
#include "./ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_exitCode(EXIT_SUCCESS)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (m_exitCode == EXIT_SUCCESS) {
        QApplication::quit();
        qDebug() << "end";
        ::_Exit(0);
    } else {
        QApplication::exit(m_exitCode);
        qDebug() << "end";
    }
}

// Restart Application
void MainWindow::on_pushButton_clicked(bool checked)
{
    m_exitCode = EXIT_RESTART;
    QApplication::closeAllWindows();
}

 

qprocess_example.zip

번호 제목 글쓴이 날짜 조회 수
공지 Qt프로그래밍(QtQuick) Beginner를 위한 글 읽는 순서 운영자 2019.01.05 85859
19 QML의 사용자 정의 Image makersweb 2023.09.17 537
18 Base64로 인코딩된 파일을 복원 makersweb 2023.08.06 429
» QProcess 예제 (프로그램 재시작) file makersweb 2023.01.25 876
16 하드디스크 드라이브 여유 공간 계산 file makersweb 2023.01.15 493
15 Qt 스마트 포인터 (QSharedPointer, QScopedPointer, QPointer) makersweb 2022.08.18 1127
14 HTTPS URL을 연결할 때 SslHandshakeFailedError 오류 makersweb 2022.07.31 355
13 응용프로그램 자동실행 설정 (on Windows) makersweb 2021.05.08 563
12 QThread 및 QMutex 예제 makersweb 2021.01.12 1346
11 QRandomGenerator 클래스를 사용하여 난수(random values) 생성 makersweb 2020.10.17 1570
10 main함수 명령줄 옵션 해석 makersweb 2020.09.01 2230
9 Qt로 데이터를 직렬화(serialization)하는 방법 makersweb 2020.08.04 2052
8 재진입(Reentrancy) 및 스레드 안전성(Thread-Safety) makersweb 2020.04.19 1216
7 컨테이너 클래스 - QVector makersweb 2020.03.17 2835
6 QLabel의 텍스트 색과 배경색을 변경 makersweb 2020.02.25 6607
5 QThread 소개 및 예제 makersweb 2019.12.25 19443
4 QScopedPointer 소개 및 사용법 makersweb 2019.11.29 1024
3 Qt애플리케이션 객체(QCoreApplication, QGuiApplication, QApplication) 에 대해서 makersweb 2019.11.11 10092
2 QPushButton 의 커스텀 이미지버튼 file makersweb 2019.11.05 6384
1 QQuickImageProvider 를 이용한 Qml 에서 이미지 표시 makersweb 2015.10.18 5995