现在我有这段代码:

请求者

#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转换为套接字的错误。

最佳答案

问题在于,您自然不会继承QObject:您无法在该类中处理插槽。

您应该这样写:

请求者

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;成员没有分配,构造和删除,但这只是将来的补充信息。

关于c++ - 将qnetworkaccessmanager连接到插槽,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19139702/

10-11 20:23