QT在错误的班级中寻找空位

时间:2018-11-03 20:51:46

标签: c++ qt qt5 qt-signals qt-slot

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

请求标头:

#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));
}

我通过运行以下命令在MainWindow类中运行此函数。

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

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

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

我仍然会提供MainWindow标头,也许是那里的错误。

#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

1 个答案:

答案 0 :(得分:3)

在以下代码中:

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

您要指出插槽属于此插槽,即它属于Request,但插槽属于MainWindow,因此解决方案是将接收方作为参数传递:

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));