Qt的新信号/插槽语法有问题-连接到简单功能

时间:2018-06-26 22:40:58

标签: c++ qt qt5 qt-signals

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

我将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:2)

使用新的连接语法时,不必指出参数的类型,因此只需使用:

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

注意: 如果您位于从connect(...)继承的类中,则仅应使用QObject,对于main,则应使用QObject::connect(...)