我正在尝试使用QNetworkAccessManager
类从网站上获取文字,但它不起作用。 When the replyFinished slot above is called, the parameter it takes is the QNetworkReply object containing the downloaded data as well as meta-data (headers, etc.)。当调用插槽时,我将获取的文本附加到QString并将其打印出来,但它会打印一个空字符串。这是我的代码:
//.pro file
TEMPLATE = app
QT += qml quick
QT += network
CONFIG += c++11
//xmlparser.h
#ifndef XMLPARSER_H
#define XMLPARSER_H
#include <QObject>
#include <QNetworkAccessManager>
class XMLParser : public QNetworkAccessManager
{
Q_OBJECT
public:
~XMLParser()=default;
static XMLParser &Instance();
Q_INVOKABLE void readXML();
signals:
finished(QNetworkReply* reply);
public slots:
void replyFinished(QNetworkReply* reply);
private:
XMLParser()=default;
XMLParser(XMLParser const&)=delete;
void operator = (XMLParser const&)=delete;
QByteArray m_text;
};
#endif // XMLPARSER_H
//xmlparser.cpp
#include <QUrl>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QEventLoop>
#include "xmlparser.h"
XMLParser &XMLParser::Instance()
{
static XMLParser instance;
return instance;
}
void XMLParser::readXML()
{
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://qt-project.org")));
}
void XMLParser::replyFinished(QNetworkReply *reply)
{
QString text;
text.append(reply->readAll());
qDebug () << "Text: " << text; //Prints out emtpy string?
}