Qt获取某地的天气情况

weather.pro (其中要加入network模块)

#-------------------------------------------------
#
# Project created by QtCreator 2019-03-30T13:54:31
#
#-------------------------------------------------

QT       += core gui
QT += network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = weather
TEMPLATE = app


SOURCES += main.cpp\
        widget.cpp

HEADERS  += widget.h

FORMS    += widget.ui
View Code

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
    QNetworkAccessManager *manager;
private slots:
    void replyFinished(QNetworkReply *);
    void on_pushButton_clicked();
};

#endif // WIDGET_H
View Code

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QUrl>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished, this, &Widget::replyFinished);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::replyFinished(QNetworkReply *reply)
{
    QString all = reply->readAll();
    ui->textBrowser->setText(all);
    reply->deleteLater();
}

void Widget::on_pushButton_clicked()
{
    qDebug()<<"abc";
    QString city = ui->lineEdit->text();
    qDebug()<<city;
    char url[256] = "http://wthrcdn.etouch.cn/weather_mini?city=";
    char *ch = city.toUtf8().data();
    sprintf(url,"%s%s",url,ch);
    manager->get(QNetworkRequest(QUrl(url)));
}
View Code

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}
View Code

图形界面:

猜你喜欢

转载自www.cnblogs.com/ACPIE-liusiqi/p/10629306.html