Как обновить исполнительный файл в qt c++ посредством перезапуска программы

Рейтинг: 0Ответов: 1Опубликовано: 22.08.2023

вот предоставляю код

void MainWindow::restartLauncher()
{
    QString appDirPath = QCoreApplication::applicationDirPath();
    QString newLauncherPath = appDirPath + "/new_mainwindow.exe";
    QString currentLauncherPath = appDirPath + "/mainwindow.exe";

    qApp->quit();
    QCoreApplication::processEvents();
    QCoreApplication::exit(); 

    QFile file("mainwindow.exe");
    file.remove();

    if (QFile::rename(newLauncherPath, currentLauncherPath))
    {
        QProcess::startDetached(currentLauncherPath);
    }
    else
    {
        QMessageBox::critical(this, "Error", "Failed to replace launcher file. Please check the files.");
    }
}

Ответы

▲ 0

Принцип скорее должен быть такой:

  1. Программа на запуске удаляет старый файл если такой имеется
  2. Если нужно обновить исполняемый файл:
    1. Программа переименовывает текущий файл в старый
    2. Программа скачивает и запускает новый файл

Т.е. у вас будет что-то в духе:

QString appDirPath = QCoreApplication::applicationDirPath();
QString oldLauncherPath = appDirPath + "/old_mainwindow.exe";
QString currentLauncherPath = appDirPath + "/mainwindow.exe";

QFile::remove(oldLauncherPath); //На самом деле должна быть на старте программы

if (/*Проверяем необходимость обновления*/) {
    if (QFile::rename(currentLauncherPath, oldLauncherPath)) {
        //Здесь мы получаем новый mainwindow.exe
        //...
        QProcess::startDetached(currentLauncherPath);
        //Завершаем программу
    } 
}

Перед осуществлением п. 1 желательно убедиться, что старый процесс завершён.