Qt 的新 signal/slot 语法出现问题 - 连接到一个简单的函数

Trouble with Qt's new signal/slot syntax - connecting to a simple function

here:所述,您可以将信号连接到一个简单的函数,如下所示:

connect(
    sender, &Sender::valueChanged,
    someFunction
);

这是我的程序:

#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>



void handleReply(QNetworkReply *reply)
{
    QString replyStr = reply->readAll();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QNetworkAccessManager manager;
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));

    return a.exec();
}

但是我遇到了一些错误:

main.cpp:18: error: call to non-static member function without an object argument
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
                       ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~

main.cpp:18: error: 'QNetworkReply' does not refer to a value
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
                                                       ^
main.cpp:18: error: expected expression
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
                                                                     ^

main.cpp:18: error: 'QNetworkReply' does not refer to a value
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
                                                                                    ^
/usr/include/x86_64-linux-gnu/qt5/QtNetwork/qnetworkreply.h:62: declared here
class Q_NETWORK_EXPORT QNetworkReply: public QIODevice

main.cpp:18: error: expected expression
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
                                                                                                  ^
                       ^

如有任何帮助,我将不胜感激。谢谢。

当您使用新的连接语法时,无需指明参数类型,因此只需使用:

#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>

#include <QDebug>

static void handleReply(QNetworkReply *reply)
{
    QString replyStr = reply->readAll();
    // do stuff
    qDebug()<< replyStr;
    reply->deleteLater();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QNetworkAccessManager manager;
    QObject::connect(&manager, &QNetworkAccessManager::finished, &handleReply);
    manager.get(QNetworkRequest(QUrl("https://www.google.com")));

    return a.exec();
}

注: 如果你在继承自 QObject 的 class 中,你应该只使用 connect(...),如果是 main 你应该使用 QObject::connect(...)