Comment utiliser QNetworkAccessManager dans une fonction hors classe ?
Bonjour,
Comment faire pour utiliser un objet, dans mon cas QNetworkAccessManager dans une fonction qui n'est pas déclarée dans une classe.
En haut du code j'ai une fonction doTask qui est appelé via un QFutureWatcher avec le mot clé setFuture:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
void doTask(QString & url)
{
QNetworkAccessManager *manager = new QNetworkAccessManager;
connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *)));
manager->get(QNetworkRequest(QUrl(url)));
}
....
...
// Prepare the vector.
QVector<QString> vector;
for (int i = 0; i < m_sl.count(); ++i)
vector.append(m_sl.at(i));
// Create a progress dialog.
QProgressDialog pg;
pg.setLabelText(QString("Downloading"));
// Create a QFutureWatcher and connect signals and slots.
QFutureWatcher<void> futureWatcher;
connect(&futureWatcher, SIGNAL(finished()), &pg, SLOT(reset()));
connect(&pg, SIGNAL(canceled()), &futureWatcher, SLOT(cancel()));
connect(&futureWatcher, SIGNAL(progressRangeChanged(int,int)), &pg, SLOT(setRange(int,int)));
connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &pg, SLOT(setValue(int)));
// Start the computation.
futureWatcher.setFuture(QtConcurrent::map(vector, &doTask));
// Display the dialog and start the event loop.
pg.exec();
futureWatcher.waitForFinished();
if(futureWatcher.isCanceled()) {
qDebug() << "Canceled";
QMessageBox::critical(this, "Canceled", "Task cancel by user!");
}
else {
qDebug() << "futureWatcher finished";
QMessageBox::information(this, "Finished", "All done !");
}
...
... |
Le problème c'est que le mot clé "this" et "connect" n'est pas reconnu car la fonction n'est pas intégrée à une classe.
donc j'ai fait:
Code:
1 2 3 4 5 6 7 8
|
void doTask(QString & url)
{
// QThread::currentThread()->msleep(500);
QNetworkAccessManager *manager = new QNetworkAccessManager;
QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), Downloader::_pSelf, SLOT(replyFinished(QNetworkReply *)));
manager->get(QNetworkRequest(QUrl(url)));
} |
j'ai ajouté QObject::connect et un pointeur sur la classe mère "Downloader", replyFinished est déclarer en statique.
il n'y a pas d'erreurs au lancement mais replyFinished n'est jamais appelé.
en haut du source j'ai:
Code:
1 2
|
Downloader *Downloader::_pSelf = NULL; |
elle est déclarée comme telle dans la classe:
Code:
1 2
|
static Downloader *_pSelf; |
dans le constructeur de la classe _pSelf est initialisée:
Code:
1 2 3 4 5 6 7 8
|
Downloader::Downloader(QStringList sl, QWidget *parent) :
QDialog(parent), m_sl(sl)
{
Downloader::_pSelf = qobject_cast<Downloader *>(this);
...
...
... |
Quelqu'un aurait une idée ?
Merci de votre aide.