PDA

View Full Version : QIODevice dosn't work inside slot



s410i
1st August 2009, 10:14
Hi!

I've wrote a class which downloads a xml file from the internet. I made it just like it was in the documentation. Now I want to save downloaded data in the file. But the QIODevice dosn't work in void HttpDownload::replyFinished(QNetworkReply *reply) slot. In constructor and other functions its OK but in slot nothing happens. This is the code:
I commented what is wrong and what works ok.

httpdownload.h


#ifndef HTTPDOWNLOAD_H
#define HTTPDOWNLOAD_H

#include <QObject>
#include <QUrl>

class QIODevice;
//class QUrl;
class QNetworkRequest;
class QNetworkAccessManager;
class QNetworkReply;


class HttpDownload : QObject
{
Q_OBJECT

public:
HttpDownload(const QUrl &downloadUrl, QIODevice *dev);
virtual ~HttpDownload();

void asynchronous(const QUrl &url = QUrl());

private:

inline void write(const char * str) {device->write(str);}

const QUrl url;
QIODevice *device;
QNetworkRequest *request;
QNetworkAccessManager *manager;
public slots:
void replyFinished(QNetworkReply* reply);

};

#endif // HTTPDOWNLOAD_H


httpdownload.cpp


#include "HttpDownload.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QIODevice>
#include <QByteArray>
#include <QNetworkReply>
#include <QIODevice>

#include <iostream>

HttpDownload::HttpDownload(const QUrl &downloadUrl, QIODevice *dev) : url(downloadUrl)
{
device = dev;

write("constructor"); // this works fine

if( url.isValid()) {
manager = new QNetworkAccessManager(this);
request = new QNetworkRequest(url);
} else {
//throw exception
}

connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
}

HttpDownload::~HttpDownload() {

if(manager != NULL)
delete manager;
if(request != NULL)
delete request;
}

void HttpDownload::asynchronous(const QUrl &downloadUrl) {

write("asynchronous func"); // this also works

if(!downloadUrl.isEmpty()) {
delete request;
request = new QNetworkRequest(downloadUrl);
}

manager->get(*request);
}

/* slot */
void HttpDownload::replyFinished(QNetworkReply *reply) {

QByteArray array;

if(! (array = reply->rawHeader(QByteArray("Location"))).isEmpty()) {
this->asynchronous(QUrl(array));
return;
}

write(" slotslotslot"); // nothing happens

}






main.cpp



#include <QtCore/QCoreApplication>
#include "HttpDownload.h"

#include <QFile>
#include <QUrl>
#include <iostream>
#include <QString>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QFile *file = new QFile("rssxml.dat");
if (!file->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
return 1;

HttpDownload hd(QUrl("http://www.google.pl"), file);
hd.asynchronous();
file->flush();
file->close();

return a.exec();
}


Thank for help
s410i

franz
1st August 2009, 11:10
Please use the code tag to format your code, not the qtclass tag.