本文最后更新于:June 30, 2023 pm

本文作者:[wangwenhai] # 概要:本文主要讲Qt5如何通过HTTP协议获取数据

最近这几天,没项目做了,突然想起来,听同学说qt做软件也还是很好玩的,无奈我不会C++ ,只能摸索,本来很简单的一个APP,做了四天,算是基本功能实现了,BUG目前没有。

总结:C++的学习成本是java的 3倍以上,想学习的可要做好心理准备。我默默的关了IDE,开始学习Java,我就不是一个学习C++的料。

【里面用到的数据来自www.showapi.com,想使用的,可以去注册申请】

软件截图:

这个简单的应用使用Qt5写的,目的为了学习QT的Http和JSON解析相关知识。

项目结构:

chartitem.h

#ifndef CHARTITEM_H
#define CHARTITEM_H

#include <QGraphicsItem>
#include <QString>
class ChartItem : public QGraphicsItem
{
public:
    ChartItem();
    ChartItem(QString title, double level  );
    QRectF boundingRect() const;
    void paint(QPainter *painter,const QStyleOptionGraphicsItem *option,
               QWidget *widget);

private:
    QString title;
    double level ;
    long heat;
    int trend;
    int xPos, yPos;
    int r ;
    int g ;
    int b ;
};

#endif // CHARTITEM_H

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QGraphicsScene>
#include <QMainWindow>
#include <QString>
#include <QtScript/QScriptEngine>
#include <QNetworkAccessManager>
#include <QTextCodec>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QPaintEvent>
#include <QAction>
#include <QMenu>
#include <QMenuBar>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private slots:
    QString replyFinished(QNetworkReply *reply);
    void getData();
    void about();
    void help();


private:
    QNetworkAccessManager *manager;
    QString urlString="http://route.showapi.com/307-2?showapi_appid=showAPI APP ID&showapi_sign=秘钥&subjectId=%2&branchId=%3&showapi_timestamp=%4";
    Ui::MainWindow *ui;
    QGraphicsScene *scene;
    QString originId;
    QString subjectId;
    QString branchId;
    QMenu *menu;
    QAction *aboutAction;
    QAction *helpAction;

};

#endif // MAINWINDOW_H

chartitem.cpp

#include "chartitem.h"
#include <QPainter>
ChartItem::ChartItem()
{
}
ChartItem::ChartItem(QString title, double level){
     r=qrand() % 255;
     g=qrand() % 255;
     b=qrand() % 255;
    this->title=title;
    this->level=level;

}
QRectF ChartItem::boundingRect() const
{
   return QRectF(-5,-5, 60, 20+this->level*2);
}
void ChartItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->setBrush(QColor(r,g,b));
    painter->drawText(0,0,this->title);
    painter->drawRect(0,10,50,this->level*2);
    painter->drawText(0,20+this->level*2, QString::number( this->level));

}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QUrl>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonParseError>
#include <QPen>
#include <QPainter>
#include "chartitem.h"
#include "chartdir.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->titleLabel->setAlignment(Qt::AlignCenter);
    this->setFixedSize(684,426);
    scene = new QGraphicsScene;
    helpAction=new QAction(tr("操作帮助"), this);
    aboutAction=new QAction(tr("作者信息"), this);
    connect(helpAction, SIGNAL(triggered()), this, SLOT(help()));
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
    menu = this->menuBar()->addMenu(tr("菜单"));
    menu->addAction(helpAction);
    menu->addAction(aboutAction);
    manager = new QNetworkAccessManager(this);
    connect(ui->searchButton,SIGNAL(clicked()),this,SLOT(getData()));
    connect(manager,SIGNAL(finished(QNetworkReply*)), this,SLOT(replyFinished(QNetworkReply*)));
}

MainWindow::~MainWindow()
{
    delete ui;
}
QString MainWindow::replyFinished(QNetworkReply *reply)
{
    QJsonParseError error;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll(),&error);
    QJsonObject apiRootObj= jsonDocument.object();
    QJsonObject apiBodyObj= apiRootObj["showapi_res_body"].toObject();
    QJsonArray dataArray= apiBodyObj["list"].toArray();
    if(!dataArray.isEmpty()){
        scene->clear();
        for(int i = 0;i<dataArray.size();i++){
            QJsonObject obj = dataArray.at(i).toObject();
            QString title=obj.value("title").toString();
            double level =obj.value("level").toString().toDouble();
            ChartItem *item=new ChartItem(title,  level );
            item->setPos( i*90,20);
            scene->addItem(item);
        }

        ui->chartView->setScene(scene);
    }else {
        QMessageBox::information(this,"提示!","当前暂时没有数据\n请认真查看专业是否和科目对应!");
    }
}
void MainWindow::getData(){
    QString queryUrl=urlString.arg(ui->originBox->currentText())
            .arg(ui->subjectBox->currentText())
            .arg(ui->branchBox->currentText())
            .arg(QDateTime::currentDateTime().toString("yyyyMMddHHmmss"));
    manager->get(QNetworkRequest(QUrl(queryUrl)));
}
void MainWindow::help(){
    QMessageBox::information(this,"帮助信息!","注意:\n1.软件所有数据来源于网络,仅仅具有参考性;\n2.文科、理科要选择正确,否则没有数据。\n3.软件作为学习交流使用,任何人都可以拿去玩。");
}
void MainWindow::about(){
    QMessageBox::information(this,"关于软件!","版本 1.0\n作者:gnik\n极光工作室出品\nwww.plstudio.xyz");
}

最后是main.cpp

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

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

    return a.exec();
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

Python科学计算库pandas的简单应用 Previous
Java回调写法实践 Next