Вопрос

I got problem with signal and slots, when I'm calling test() function from main function, signal and slots aren't working (they aren't invoking) , but when I'm calling code from test() directly in main function, signal and slots are invoking! What I'm doing wrong? Second question, is there any way to return response? I need to find something on page.

main.cpp

void test()
{
    httpManager manager;
    manager.sendRequest("http://google.com/");
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MfzBot w;
    w.show();
    test();

    return a.exec();
}

working main.cpp :

void test()
{
    httpManager manager;
    manager.sendRequest("http://google.com/");
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MfzBot w;
    w.show();

    httpManager manager;
    manager.sendRequest("http://google.com/");

    return a.exec();
}

httpmanager.cpp :

httpManager::httpManager()
{
    QObject::connect(manager, SIGNAL(finished(QNetworkReply*)),
               this, SLOT(replyFinished(QNetworkReply*)));
}

QNetworkCookieJar cookies;

void httpManager::sendRequest(const char* url)
{
    QNetworkProxyFactory::setUseSystemConfiguration (true);

    QByteArray outArray;
    QDataStream stream(&outArray, QIODevice::WriteOnly);

    manager->setCookieJar(cookies);

    QNetworkRequest request(QUrl(url));

    manager->post(request, outArray);
}

void httpManager::replyFinished(QNetworkReply *reply)
{
    qDebug() << "ok! ";
    qDebug() << reply->readAll();
}

httpmanager.h :

class httpManager : public QObject
{
    Q_OBJECT

public:
    httpManager();

protected slots:
    void replyFinished(QNetworkReply *reply);

public:
    void sendRequest(const char *url);

private:
    QNetworkCookieJar *cookies = new QNetworkCookieJar();
    QNetworkAccessManager *manager = new QNetworkAccessManager();
};
Это было полезно?

Решение 2

Your object "manager" is destroyed right after test() function is finished. To avoid this try to dynamically create object:

httpManager *manager;

void test()
{
    manager = new httpManager();
    manager->sendRequest("http://google.com/");
}

Notice that "httpManager *manager" is outside of any function.

Now your "manager" object is somewhere in memory (called heap) and not destroyed when test() function exits. Beware, this method not so good because "manager" now is global variable, that's not good way in Object Oriented Programming, but for the first time it doesn't matters.

Другие советы

The problem with the first code is that the object "manager" which has a type of "httpManager" is created on stack after calling the function "test()" and respectively is destroyed when test() returns. Therefore there is no "manager" object when "test()" returns and the signals and slots wont work. While in the latter code "manager" exists until the application is terminated.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top