Pergunta

I want QNetworkAccessManager to run HTTP requests in seperate thread. Currently in QT4.6 it is running in the same thread and it causes my browser to hang. This feature is recently introduced in QT 4.8 but now I cant switch to QT 4.8. therefore I want to implement this in QT 4.6 for QNetworkAccessManager .

Can anyone help me on this?

Foi útil?

Solução

There are more than a couple ways to accomplish what you desire.

First, make sure you are using the QNetworkAccessManager correctly. By default HTTP requests, such as:

QNetworkAccessManager *manager= new QNetworkAccessManager(this);
manager->post(QNetworkRequest(QUrl("http://www.example.com/")));

are made asynchronously, but this does not necessarily mean they are in their own thread. If you make a bunch of these calls, you could slow down the containing thread.

Now, one way that I use to ensure requests are made in separate threads is to create an entire QObject/QWidget for my QNetworkAccessManager like this:

(Header)

class Manager : public QWidget
{
    Q_OBJECT

public:
    Manager(QWidget *parent=0);
    QNetworkAccessManager *manager;
private slots:
    void replyFinished(QNetworkReply* data);
};

//... ... ...
//Later in the main thread declaration
//... ... ...

class MainBrowserWindow : public QWidget
{
     //.... ... .. .. 
     //Other stuff for the main window

     Manager managingWidget;
     //this ensures that a new thread will be created and initialized
     //alongside our MainBrowserWindow object (which is initialized in main.cpp)

};

(Implementation)

Manager::Manager(QWidget *parent): QWidget (parent){
    //Initialize the widget here, set the geometry title and add other widgets
    //I usually make this a QWidget so that it can double as a
    //pop-up progress bar.

    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
}

Now you can make calls to your manager object from your main window's implementation with calls like:

managingWidget.manager->post()

Once again, this is only one of the many methods you may use, and in some instances the QNetworkAccessManager will automatically place requests in their own thread. But this should force the operating system to place all of your requests in a thread separate from your main thread.

Outras dicas

Read about threads in Qt, and make your own thread which recieve signal for each URL to process, and emit some signal back to the main thread when the HTTP reply is handled.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top