Qt 6 C++ 桌面天气预报应用开发指南
一个使用 Qt 6 + C++ 开发的桌面天气预报应用。从零开始实现,支持输入城市名称查询当前天气和未来 7 天预报。
前提条件
第一步
我们使用 Open-Meteo 免费天气 API(无需 API Key,非商业免费使用,数据准确):
第二步
注册 OpenWeatherMap 获取免费 API Key:https://openweathermap.org/api (只需邮箱注册,立即可用)
首先需要通过城市名获取经纬度,我们使用另一个免费 API:OpenWeatherMap 的 Geocoding API(免费注册后获取 API Key,支持每天 1000 次调用):
http://api.openweathermap.org/geo/1.0/direct?q=城市名&limit=1&appid=你的KEY
大体思路
通过城市名获取地理坐标,再利用经纬度坐标输入来获取天气输出。
功能特点
- 输入城市名称(支持中文或英文,如 "Beijing" 或 "Shanghai,CN")
- 以下为获取地理数据返回 经纬度
void MainWindow::onGeoReplyFinished(QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
QMessageBox::critical(this, "错误", "位置查询失败:" + reply->errorString());
reply->deleteLater();
return;
}
QByteArray data = reply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonArray array = doc.array();
if (array.isEmpty()) {
QMessageBox::(, , );
reply->();
;
}
QJsonObject obj = array.().();
lat = obj[].();
lon = obj[].();
QString cityName = obj[].() + + obj[].();
reply->();
QString weatherUrl = (
).(lat).(lon);
weatherManager->(((weatherUrl)));
ui->currentWeatherLabel->(().(cityName));
}


