QT | Qt实现软件在线更新

在许多情况下,我们希望我们的软件能够自动检查更新,并在有新版本时提示用户。

检查更新

首先,我们需要一个函数来检查是否有新的版本可用。在这个例子中,我们使用QNetworkAccessManager来发送一个GET请求到我们的更新服务器。我们将当前的版本号作为查询参数添加到URL中。

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

    QString version = "1.0.1";
    a.setApplicationVersion(version);

    MainWindow w;
    w.show();
    return a.exec();
}
void MainWindow::checkForUpdates()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished, this, &MainWindow::onCheckForUpdatesFinished);

    QUrl url("https://XXX.XX/XXX/index.php/Home/Update/XXX");
    QUrlQuery query;
    query.addQueryItem("version", QApplication::applicationVersion());
    url.setQuery(query);

    QSslConfiguration config = QSslConfiguration::defaultConfiguration();
    config.setPeerVerifyMode(QSslSocket::VerifyNone);
    config.setProtocol(QSsl::AnyProtocol);

    QNetworkRequest request(url);
    request.setSslConfiguration(config);

    manager->get(request);
}

处理服务器的响应

当我们收到服务器的响应时,我们需要解析它来确定是否有新的版本可用。在这个例子中,我们假设服务器返回一个JSON对象,其中包含一个updateFileUrl字段,这个字段指向新版本的下载链接。

void MainWindow::onCheckForUpdatesFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll());
        QJsonObject jsonObj = jsonDoc.object();

        if (jsonObj.contains("updateFileUrl")) {
            QString downloadLink = jsonObj["updateFileUrl"].toString();
            QString latestVersion = jsonObj["latestVersion"].toString();
            QString updateContent = jsonObj["updateContent"].toString();

            // 提示用户有新的版本可用,并询问他们是否想要更新
            // 如果用户选择更新,我们开始下载新版本的软件
        }
    }
    reply->deleteLater();
}

下载新版本

如果用户选择更新,我们开始下载新版本的软件。我们再次使用QNetworkAccessManager来发送一个GET请求到新版本的下载链接。

void MainWindow::onDownloadFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QUrl url = reply->url();
        QString filename = QFileInfo(url.path()).fileName();
        QString newFilePath = QCoreApplication::applicationDirPath() + "/" + filename;
        QFile file(newFilePath);
        if (file.open(QIODevice::WriteOnly)) {
            file.write(reply->readAll());
            file.close();

            // 启动新版本的软件,并关闭当前的软件
        }
    }
    reply->deleteLater();
}

启动新版本

最后,我们启动新版本的软件,并关闭当前的软件。

QProcess process;
process.setProgram(newFilePath);
process.startDetached();

QApplication::quit();
使用 Hugo 构建
主题 StackJimmy 设计