上一章我们了解了NetWorker类的简单实现。不仅如此,我们还提到了几个 C++ 开发时常用的设计模式。这些在接下来得代码中依然会用到。

    现在我们先来研究下 OpenWeatherMap 的相关 API。之所以选择 OpenWeatherMap,主要是因为这个网站提供了简洁的 API 接口,非常适合示例程序,并且其开发也不需要额外申请 App ID。OpenWeatherMap 的 API 可以选择返回 JSON 或者 XML,这里我们选择使用 JSON 格式。在进行查询时,OpenWeatherMap 支持使用城市名、地理经纬度以及城市 ID,为简单起见,我们选择使用城市名。我们先来看一个例子:http://api.openweathermap.org/data/2.5/weather?q=Beijing,cn&mode=json&units=metric&lang=zh_cn。下面是这个链接的参数分析:

    参数名字传入值说明
    qBeijing,cn查询中国北京的天气
    modejson返回格式为 JSON
    unitsmetric返回单位为公制
    langzh_cn返回语言为中文

    点击链接,服务器返回一个 JSON 字符串(此时你应该能够使用浏览器看到这个字符串):

    1. {"coord":{"lon":116.397232,"lat":39.907501},"sys":{"country":"CN","sunrise":1381530122,"sunset":1381570774},"weather":[{"id":800,"main":"Clear","description":"晴","icon":"01d"}],"base":"gdps stations","main":{"temp":20,"pressure":1016,"humidity":34,"temp_min":20,"temp_max":20},"wind":{"speed":2,"deg":50},"clouds":{"all":0},"dt":1381566600,"id":1816670,"name":"Beijing","cod":200}

    我们从这里找到 JSON 各个字段的含义。现在我们关心的是:时间(dt);气温(temp);气压(pressure);湿度(humidity)和天气状况(weather)。基于此,我们设计了WeatherInfo类,用于封装服务器返回的信息:

    1. class WeatherDetail
    2. {
    3. public:
    4. WeatherDetail();
    5. ~WeatherDetail();
    6.  
    7. QString desc() const;
    8. void setDesc(const QString &desc);
    9.  
    10. QString icon() const;
    11. void setIcon(const QString &icon);
    12.  
    13. private:
    14. class Private;
    15. friend class Private;
    16. Private *d;
    17. };
    18.  
    19. class WeatherInfo
    20. {
    21. public:
    22. WeatherInfo();
    23. ~WeatherInfo();
    24.  
    25. QString cityName() const;
    26. void setCityName(const QString &cityName);
    27.  
    28. quint32 id() const;
    29. void setId(quint32 id);
    30.  
    31. QDateTime dateTime() const;
    32. void setDateTime(const QDateTime &dateTime);
    33.  
    34. float temperature() const;
    35. void setTemperature(float temperature);
    36.  
    37. float humidity() const;
    38. void setHumidity(float humidity);
    39.  
    40. float pressure() const;
    41. void setPressure(float pressure);
    42.  
    43. QList<WeatherDetail *> details() const;
    44. void setDetails(const QList<WeatherDetail *> details);
    45.  
    46. private:
    47. class Private;
    48. friend class Private;
    49. Private *d;
    50. };
    51.  
    52. QDebug operator <<(QDebug dbg, const WeatherDetail &w);
    53. QDebug operator <<(QDebug dbg, const WeatherInfo &w);

    WeatherInfoWeatherDetail两个类相互合作存储我们所需要的数据。由于是数据类,所以只有单纯的 setter 和 getter 函数,这里不再把源代码写出来。值得说明的是最后两个全局函数:

    1. QDebug operator <<(QDebug dbg, const WeatherDetail &w);
    2. QDebug operator <<(QDebug dbg, const WeatherInfo &w);

    我们重写了<<运算符,以便能够使用类似qDebug() << weatherInfo;这样的语句进行调试。它的实现是这样的:

    1. QDebug operator <<(QDebug dbg, const WeatherDetail &w)
    2. {
    3. dbg.nospace() << "("
    4. << "Description: " << w.desc() << "; "
    5. << "Icon: " << w.icon()
    6. << ")";
    7. return dbg.space();
    8. }
    9.  
    10. QDebug operator <<(QDebug dbg, const WeatherInfo &w)
    11. {
    12. dbg.nospace() << "("
    13. << "id: " << w.id() << "; "
    14. << "City name: " << w.cityName() << "; "
    15. << "Date time: " << w.dateTime().toString(Qt::DefaultLocaleLongDate) << ": " << endl
    16. << "Temperature: " << w.temperature() << ", "
    17. << "Pressure: " << w.pressure() << ", "
    18. << "Humidity: " << w.humidity() << endl
    19. << "Details: [";
    20. foreach (WeatherDetail *detail, w.details()) {
    21. dbg.nospace() << "( Description: " << detail->desc() << ", "
    22. << "Icon: " << detail->icon() << "), ";
    23. }
    24. dbg.nospace() << "] )";
    25. return dbg.space();
    26. }

    这两个函数虽然比较长,但是很简单,这里不再赘述。

    下面我们来看主窗口:

    1. class MainWindow : public QMainWindow
    2. {
    3. Q_OBJECT
    4. public:
    5. MainWindow(QWidget *parent = 0);
    6. ~MainWindow();
    7.  
    8. private:
    9. class Private;
    10. friend class Private;
    11. Private *d;
    12. };

    正如前面所说的,这里依然使用了 d 指针模式。头文件没有什么可说的。MainWindow::Private的实现依旧简单:

    1. class MainWindow::Private
    2. {
    3. public:
    4. Private()
    5. {
    6. netWorker = NetWorker::instance();
    7. }
    8.  
    9. void fetchWeather(const QString &cityName) const
    10. {
    11. netWorker->get(QString("http://api.openweathermap.org/data/2.5/weather?q=%1&mode=json&units=metric&lang=zh_cn").arg(cityName));
    12. }
    13.  
    14. NetWorker *netWorker;
    15. };

    我们将MainWindow所需要的NetWorker作为MainWindow::Private的一个成员变量。MainWindow::Private提供了一个fetchWeather()函数。由于NetWorker提供的函数都是相当底层的,为了提供业务级别的处理,我们将这样的函数封装在MainWindow::Private中。当然,你也可以在NetWorker中直接提供类似的函数,这取决于你的系统分层设计。

    1. MainWindow::MainWindow(QWidget *parent)
    2. : QMainWindow(parent),
    3. d(new MainWindow::Private)
    4. {
    5. QComboBox *cityList = new QComboBox(this);
    6. cityList->addItem(tr("Beijing"), QLatin1String("Beijing,cn"));
    7. cityList->addItem(tr("Shanghai"), QLatin1String("Shanghai,cn"));
    8. cityList->addItem(tr("Nanjing"), QLatin1String("Nanjing,cn"));
    9. QLabel *cityLabel = new QLabel(tr("City: "), this);
    10. QPushButton *refreshButton = new QPushButton(tr("Refresh"), this);
    11. QHBoxLayout *cityListLayout = new QHBoxLayout;
    12. cityListLayout->setDirection(QBoxLayout::LeftToRight);
    13. cityListLayout->addWidget(cityLabel);
    14. cityListLayout->addWidget(cityList);
    15. cityListLayout->addWidget(refreshButton);
    16.  
    17. QVBoxLayout *weatherLayout = new QVBoxLayout;
    18. weatherLayout->setDirection(QBoxLayout::TopToBottom);
    19. QLabel *cityNameLabel = new QLabel(this);
    20. weatherLayout->addWidget(cityNameLabel);
    21. QLabel *dateTimeLabel = new QLabel(this);
    22. weatherLayout->addWidget(dateTimeLabel);
    23.  
    24. QWidget *mainWidget = new QWidget(this);
    25. QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget);
    26. mainLayout->addLayout(cityListLayout);
    27. mainLayout->addLayout(weatherLayout);
    28. setCentralWidget(mainWidget);
    29. resize(320, 120);
    30. setWindowTitle(tr("Weather"));
    31.  
    32. connect(d->netWorker, &NetWorker::finished, [=] (QNetworkReply *reply) {
    33. qDebug() << reply;
    34. QJsonParseError error;
    35. QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll(), &error);
    36. if (error.error == QJsonParseError::NoError) {
    37. if (!(jsonDocument.isNull() || jsonDocument.isEmpty()) && jsonDocument.isObject()) {
    38. QVariantMap data = jsonDocument.toVariant().toMap();
    39. WeatherInfo weather;
    40. weather.setCityName(data[QLatin1String("name")].toString());
    41. QDateTime dateTime;
    42. dateTime.setTime_t(data[QLatin1String("dt")].toLongLong());
    43. weather.setDateTime(dateTime);
    44. QVariantMap main = data[QLatin1String("main")].toMap();
    45. weather.setTemperature(main[QLatin1String("temp")].toFloat());
    46. weather.setPressure(main[QLatin1String("pressure")].toFloat());
    47. weather.setHumidity(main[QLatin1String("humidity")].toFloat());
    48. QVariantList detailList = data[QLatin1String("weather")].toList();
    49. QList<WeatherDetail *> details;
    50. foreach (QVariant w, detailList) {
    51. QVariantMap wm = w.toMap();
    52. WeatherDetail *detail = new WeatherDetail;
    53. detail->setDesc(wm[QLatin1String("description")].toString());
    54. detail->setIcon(wm[QLatin1String("icon")].toString());
    55. details.append(detail);
    56. }
    57. weather.setDetails(details);
    58.  
    59. cityNameLabel->setText(weather.cityName());
    60. dateTimeLabel->setText(weather.dateTime().toString(Qt::DefaultLocaleLongDate));
    61. }
    62. } else {
    63. QMessageBox::critical(this, tr("Error"), error.errorString());
    64. }
    65. reply->deleteLater();
    66. });
    67. connect(refreshButton, &QPushButton::clicked, [=] () {
    68. d->fetchWeather(cityList->itemData(cityList->currentIndex()).toString());
    69. });
    70. }
    71.  
    72. MainWindow::~MainWindow()
    73. {
    74. delete d;
    75. d = 0;
    76. }

    接下来我们来看MainWindow的构造函数和析构函数。构造函数虽然很长但是并不复杂,主要是对界面的构建。我们这里略过这些界面的代码,直接看两个信号槽的连接。

    1. connect(d->netWorker, &NetWorker::finished, [=] (QNetworkReply *reply) {
    2. QJsonParseError error;
    3. QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll(), &error);
    4. if (error.error == QJsonParseError::NoError) {
    5. if (!(jsonDocument.isNull() || jsonDocument.isEmpty()) && jsonDocument.isObject()) {
    6. QVariantMap data = jsonDocument.toVariant().toMap();
    7. WeatherInfo weather;
    8. weather.setCityName(data[QLatin1String("name")].toString());
    9. QDateTime dateTime;
    10. dateTime.setTime_t(data[QLatin1String("dt")].toLongLong());
    11. weather.setDateTime(dateTime);
    12. QVariantMap main = data[QLatin1String("main")].toMap();
    13. weather.setTemperature(main[QLatin1String("temp")].toFloat());
    14. weather.setPressure(main[QLatin1String("pressure")].toFloat());
    15. weather.setHumidity(main[QLatin1String("humidity")].toFloat());
    16. QVariantList detailList = data[QLatin1String("weather")].toList();
    17. QList<WeatherDetail *> details;
    18. foreach (QVariant w, detailList) {
    19. QVariantMap wm = w.toMap();
    20. WeatherDetail *detail = new WeatherDetail;
    21. detail->setDesc(wm[QLatin1String("description")].toString());
    22. detail->setIcon(wm[QLatin1String("icon")].toString());
    23. details.append(detail);
    24. }
    25. weather.setDetails(details);
    26.  
    27. cityNameLabel->setText(weather.cityName());
    28. dateTimeLabel->setText(weather.dateTime().toString(Qt::DefaultLocaleLongDate));
    29. }
    30. } else {
    31. QMessageBox::critical(this, tr("Error"), error.errorString());
    32. }
    33. reply->deleteLater();
    34. });
    35. connect(refreshButton, &QPushButton::clicked, [=] () {
    36. d->fetchWeather(cityList->itemData(cityList->currentIndex()).toString());
    37. });

    由于使用了 Qt5,我们选择新的连接语法。第一个connect()函数中,我们按照 API 文档中描述的那样对服务器返回的 JSON 字符串进行解析,然后将数据填充到一个WeatherInfo的对象。然后操作界面的两个控件显示数据。值得注意的是函数的最后一行,reply->deleteLater();。当网络请求结束时,delete 服务器返回的QNetworkReply对象是用户的责任。用户需要选择一个恰当的时机进行 delete 操作。但是,我们不能直接在finiahed()信号对应的槽函数中调用delete运算符。相反,我们需要使用deleteLater()函数,正如前面代码中显示的那样。第二个槽函数则相对简单,仅仅是重新获取新的数据。

    选择我们可以运行下程序了:

    weather 示例