2012-10-20 92 views
0

我有一些奇怪的東西我有這樣的代碼:Qt的要求從來沒有觸發成品()信號

我想我知道我不什麼是錯的,但知道如何解決它。 這是我有: 當我把斷點在int測試= 0; 在它到達HttpClient中的httpFinished()槽之前,mybe這是問題嗎? 在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()函數是在私有槽:從不觸發,爲什麼呢?

更新問題

回答

1

由於HttpClientQNetworkAccessManager對象的線程內創建,它們自動地屬於該線程(見QObject::moveToThread),並且它們都需要一個事件循環在該線程運行時,QNAM根本無法做任何工作,並且您的派生類能夠執行這些插槽。

你可以在run()添加調用QThread::exec()來運行事件循環(如果你使用QThread):

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

或創建並啓動QEventLoopquit()插槽在某處被連接到停止環(例如在類HttpClient一個finished()信號時,工作完成後,你會發出):

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

而且,since Qt 4.8,QNetworkAccessManager是多線程的,所以你可能不需要自己使用線程。

+0

謝謝我知道在4.8它是MT,但我需要在線程中做更多的工作,不僅http http req,線程如何知道它的完成? – user63898

+0

@ user63898線程不會自行停止,您需要調用其插槽'quit()'(或將其連接到應答「finished()」信號)來停止事件循環和線程。 – alexisdm

+0

錯誤C3861:'exec':標識符未找到,可以嗎? – user63898