0

我有一些非常奇怪的东西我有这个代码:

我想我知道出了什么问题,但我不知道如何解决它。这就是我所拥有的:当我在 int test = 0 中放置断点时;它在到达 HttpClient 中的 httpFinished() 插槽之前到达那里,这就是问题所在吗?在 main.cpp

---------------------------------------------------------------------------------------------------------
@while (i.hasNext())
{
i.next();

ThreadWorker* pThreadWorker = new ThreadWorker();
pThreadWorker->setUrl(sUrl);
QThreadPool::globalInstance()->start(pThreadWorker);
}
QThreadPool::globalInstance()->waitForDone();



---------------------------------------------------------------------------------------------------------
void ThreadWorker::run()
{
  startWork();
}

void ThreadWorker::startWork()
{
 m_pHttpClient = new HttpClient();
 m_pHttpClient->startRequest(m_url);
 int test = 0;


}

--------------------------------- HttpClient  based on the http example from Qt -----------------------------------

HttpClient::HttpClient()
{
  m_networkManager = new QNetworkAccessManager(this);
  connect(m_networkManager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
            this, SLOT(slotAuthenticationRequired(QNetworkReply*,QAuthenticator*)));

 #ifndef QT_NO_OPENSSL
    connect(m_networkManager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
            this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
 #endif
}



void HttpClient::startRequest(QUrl url)
{
   m_url.setUrl("http://qt.nokia.com/");
  QNetworkRequest request; 
  request.setUrl(m_url);

 reply = m_networkManager->get(request);


 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
         this, SLOT(slotError(QNetworkReply::NetworkError)));

 connect(reply,SIGNAL(finished()),
            this, SLOT(httpFinished()));

    connect(reply, SIGNAL(readyRead()),
            this, SLOT(httpReadyRead()));

    connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
            this, SLOT(updateDataReadProgress(qint64,qint64)));


}

私有插槽下的 httpFinished() 函数:从未触发,为什么?

更新了问题

4

1 回答 1

1

由于HttpClientandQNetworkAccessManager对象是在线程中创建的,它们自动属于该线程(请参阅QObject::moveToThread参考资料),并且它们都需要在该线程中运行一个事件循环,以便 QNAM 完成任何工作,并且您的QObject派生类能够执行插槽。

QThread::exec()您可以添加对in的调用以run()运行该事件循环(如果您使用的是QThread):

void Thread::run()
{
    startWork();
    exec();
}

或创建并启动一个QEventLoopquit()插槽必须连接到某处以停止循环(例如,当工作完成时您将发出finished()的类中的信号):HttpClient

void ThreadWorker::run()
{
    startWork();
    QEventLoop loop;
    QObject::connect(m_pHttpClient, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec(); 
}

此外,由于 Qt 4.8QNetworkAccessManager多线程的,因此您可能不需要自己使用线程。

于 2012-10-20T20:13:58.323 回答