作为我之前提出的问题的后续,我现在面临的问题是,即使请求的页面存在(至少来自 Web 浏览器),下载的数据也是空的。
我猜数据实际上是下载的,因为fileDownloaded()
调用了调试行,然后将来自的信号downloaded()
传递到,然后每次单击按钮时都会SLOT(loadText()
打印到控制台"STRING: "
主窗口.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <string.h>
#include <iostream>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QByteArray>
#include <QTextCodec>
#include <QDebug>
using namespace std;
namespace Ui {
class MainWindow;
}
class DataFetch : public QObject
{
Q_OBJECT
public:
explicit DataFetch(QUrl url, QObject *parent=0);
virtual ~DataFetch();
QByteArray downloadedData() const;
signals:
void downloaded();
public slots:
void fileDownloaded(QNetworkReply* reply);
private:
QNetworkAccessManager m_webManager;
QByteArray m_downloaded;
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
DataFetch * m;
public slots:
void btnClickHandler();
private slots:
void loadText();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
主窗口.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
DataFetch::DataFetch(QUrl url, QObject *parent):
QObject(parent)
{
connect(&m_webManager, SIGNAL(finished(QNetworkReply*)), SLOT(fileDownloaded(QNetworkReply*)));
QNetworkRequest request(url);
m_webManager.get(request);
}
DataFetch::~DataFetch() { }
void DataFetch::fileDownloaded(QNetworkReply *reply)
{
QByteArray m_downloaded = reply->readAll();
qDebug() << "received reply";
reply->deleteLater();
emit downloaded();
}
QByteArray DataFetch::downloadedData() const
{
return m_downloaded;
}
void MainWindow::loadText()
{
cout << "STRING: " << m->downloadedData().data() << endl;
ui->lblText->setText(m->downloadedData());
}
void MainWindow::btnClickHandler()
{
QUrl textURL = QUrl("http://192.168.2.7/index.html");
m = new DataFetch(textURL, this);
connect(m, SIGNAL(downloaded()), SLOT(loadText()));
}
main.cpp与默认模板保持不变..
再次感谢您的帮助!