我有一个单独的类,用于使用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
在以下代码中:
connect(manager, SIGNAL(finished(QNetworkReply*)), this, slot);
您指出插槽属于此,即它属于Request,但插槽属于MainWindow,因此解决方案是将接收器作为参数传递:
请求.h
...
void make_request(const QUrl & url, QObject *receiver, const char *slot);
...
请求.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));