한국어
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 85858
39 Qt Bluetooth 관련 기능 확인 사항 makersweb 2018.07.10 763
38 Q_D매크로와 d-pointer file makersweb 2019.05.07 759
37 Qt for MCU 1.0 릴리즈 makersweb 2019.12.10 751
36 싱글 샷(Single-Shot) 시그널/슬롯 연결 makersweb 2021.05.12 751
35 2020년에 변경되는 Qt 오퍼 (Qt offering changes 2020) [2] j2doll 2020.01.31 720
34 단일 인스턴스 Qt 응용 프로그램(Single-instance Application) makersweb 2022.06.23 700
33 Qt 응용프로그램에서 PDF 문서 렌더링 file makersweb 2021.09.23 677
32 Qt5Compat 라이브러리를 사용하여 Qt5에서 Qt6로 포팅 [2] makersweb 2020.12.05 672
31 Qt Bluetooth Low Energy 개요 makersweb 2022.02.13 661
30 QML에서 D-Bus 통신 file makersweb 2023.03.15 649
29 클라우드용 Qt file makersweb 2024.01.16 638
28 Qt Marketplace 발표 makersweb 2019.12.02 617
27 Embedded Linux 에서 Qt 및 Graphics Stack file 운영자 2020.05.27 612
26 QProcess 보안 권고 리뷰 file makersweb 2022.09.18 597
25 최초의 Qt 6.0 스냅샷 제공 (First Qt 6.0 Snapshot Available) j2doll 2020.06.21 591
24 QML과 코루틴(Coroutines) makersweb 2020.11.03 577
23 clazy 로 13개의 시그널, 슬롯 오류 해결 makersweb 2022.08.23 566
22 OpacityMask 예제 file makersweb 2023.01.26 564
21 응용프로그램 자동실행 설정 (on Windows) makersweb 2021.05.08 563
20 Qt Safe Renderer 개요 file makersweb 2022.09.08 542