QT 寻找插槽错误 class

QT looking for slot in wrong class

我有一个单独的 class 用于使用 QNetwork 发出 GET 请求,如下所示。

请求header:

#ifndef REQUEST_H
#define REQUEST_H

#include <QUrl>
#include <QObject>

class Request : public QObject
{
    Q_OBJECT

public:
    void make_request(QUrl url, const char* slot);
};

#endif // REQUEST_H

请求来源:

#include "request.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>

void Request::make_request(const QUrl url, const char* slot)
{
    QNetworkAccessManager* manager = new QNetworkAccessManager();
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, slot);

    QNetworkReply* reply = manager->get(QNetworkRequest(url));
}

我运行这个函数在我的MainWindowclass下面运行。

request.make_request(QUrl("{ApiUrl}"), SLOT(parse_trending(QNetworkReply*)));

但是,它会产生错误 QObject::connect: No such slot Request::parse_trending(QNetworkReply*) in {MainWindow}

我已将 Q_OBJECT 宏添加到我的 header 文件中,但我仍然不知道是什么导致了此错误。

我还是会提供我的 MainWindow header,也许错误就在那里。

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QNetworkReply>
#include <QObject>
#include "util/request.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    Request request;

public slots:
    void parse_trending(QNetworkReply *reply);
};

#endif // MAINWINDOW_H

在下面的代码中:

connect(manager, SIGNAL(finished(QNetworkReply*)), this, slot);

你指的是slot属于this,即属于Request但是slot属于MainWindow,所以解决方法是将receiver作为参数传递:

request.h

...
void make_request(const QUrl & url, QObject *receiver, const char *slot);
...

request.cpp

void Request::make_request(const QUrl url, QObject *receiver, const char* slot)
{
    QNetworkAccessManager* manager = new QNetworkAccessManager();
    connect(manager, SIGNAL(finished(QNetworkReply*)), receiver, slot);
    manager->get(QNetworkRequest(url));
}

request.make_request(QUrl("{ApiUrl}"), this, SLOT(parse_trending(QNetworkReply*)));

另一个选项使用 std::function (#include <functional>):

void Request::make_request(const QUrl & url, std::function<void (QNetworkReply *)> slot)
{
    QNetworkAccessManager* manager = new QNetworkAccessManager();
    connect(manager, &QNetworkAccessManager::finished, slot);
    manager->get(QNetworkRequest(url));
}

request.make_request(QUrl("{ApiUrl}"), std::bind(&MainWindow::parse_trending, this, std::placeholders::_1));