// MainWindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public Q_SLOTS:
void button1Click();
void reply(QNetworkReply *reply);
private:
Ui::MainWindow *ui;
};
// MainWindow.cpp
#include <QUrl>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QObject::connect(ui->pushButton_1, SIGNAL(clicked()), this, SLOT(button1Click()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::reply(QNetworkReply *reply)
{
qDebug() << reply->readAll().size(); // 获取的网页数据大小,0表示下载失败
reply->deleteLater();
}
void MainWindow::button1Click()
{
QNetworkAccessManager *nm = new QNetworkAccessManager(this);
// 必须用信号和槽连接
connect(nm, SIGNAL(finished(QNetworkReply*)), this, SLOT(reply(QNetworkReply*)));
// 需要下载的网页url地址,有些网址用这种简单方法无法获取数据
QNetworkRequest request(QUrl("http://www.baidu.com"));
nm->get(request);
}
Qt简单下载网页
点赞
收藏