检查更新
首先,我们需要一个函数来检查是否有新的版本可用。在这个例子中,我们使用 QNetworkAccessManager 来发送一个 GET 请求到我们的更新服务器。我们将当前的版本号作为查询参数添加到 URL 中。
1 2 3 4 5 6 7 8 9 10 11
| 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(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| 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 字段,这个字段指向新版本的下载链接。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 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 请求到新版本的下载链接。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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(); }
|
启动新版本
最后,我们启动新版本的软件,并关闭当前的软件。
1 2 3 4 5
| QProcess process; process.setProgram(newFilePath); process.startDetached();
QApplication::quit();
|