将qnetworkaccessmanager连接到插槽

时间:2013-10-02 14:41:40

标签: c++ qt qtcore qt-signals qtnetwork

现在我有了这段代码:

requester.h

#ifndef REQUESTER_H
#define REQUESTER_H

#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtCore/QtCore>
#include <QVector>
#include <QObject>

class Requester
{
Q_OBJECT
public:
    Requester();
    ~Requester();
    QString get_last_reply();
    void send_request();
private:
    QNetworkAccessManager *manager;
    QVector<QString> replies;
public slots:
    void get_reply(QNetworkReply *reply);
};

#endif // REQUESTER_H

requester.cpp

#include "requester.h"

Requester::Requester()
{
    manager = new QNetworkAccessManager;
}

Requester::~Requester() {
    delete manager;
}


void Requester::get_reply(QNetworkReply *reply) {
    QByteArray res = reply->readAll();
    QString data = res.data();
    replies.push_back(data);
}

QString Requester::get_last_reply() {
    QString res =  replies.back();
    replies.pop_back();
    return res;
}
void Requester::send_request() {
    QObject::connect(manager, SIGNAL(finished(QNetworkReply*)), this,     SLOT(get_reply(QNetworkReply*)));
    manager->get(QNetworkRequest(QUrl("http://google.com")));
}

这个错误:

no matching function for call to 'QObject::connect(QNetworkReply*&, const char*, Requester* const, const char*)'

出了什么问题?我曾尝试使用connect而不是QObject :: connect,但是有一个错误,即无法将QNetworkAccessmanager转换为socket。

1 个答案:

答案 0 :(得分:1)

问题是你没有继承QObject,所以很自然:你不能在那个类中处理插槽。

你应该写这样的东西:

requester.h

class Requester : public QObject
{
Q_OBJECT
public:
    explicit Requester(QObject *parent);
...

requester.cpp

#include "requester.h"

Requester::Requester(QObject *p)
    : QObject(p)
    , manager(new QNetworkAccessManager)
{
}
...

此外,在这种情况下,在堆上构造QNetworkAccessManager而不是堆栈几乎没有意义。您可以拥有一个QNetworkAccessManager m_networkAccessManager;没有分配,构造和删除的成员,但这只是未来的附加信息。