2016-08-04 40 views
0

有一個在主主窗口類的狹槽(GUI),其在QTextBrowser中被顯示的數據:Qt的C++從線程發出,在槽GUI

void MainWindow::setLogs(QString param, QString text) { 
    qDebug()<<text; 
    ui->Logs->append(text); 
} 

有,在一個運行一個類單獨的線程,使得POST的搜索和在QTextBrowser中被插入數據:

QNetworkRequest request(apiUrl); 

request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0"); 
request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
request.setRawHeader("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3"); 
request.setRawHeader("Accept-Encoding", "identity"); 
request.setRawHeader("Connection", "keep-alive"); 
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded"); 

reply = manager.post(request, "data="+data); 

connect(reply, &QNetworkReply::finished,this, &MakePost::getReplyFinished); 
connect(reply, &QNetworkReply::readyRead, this, &MakePost::readyReadReply); 
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(GetError())); 

void MakePost::readyReadReply() 
{ 
    QString GetRes = QString::fromUtf8(reply->readAll()); 
    qDebug() << "GetRes: " + GetRes; 
    emit SendLog(GetRes); 
} 

呼叫線程:

QThread *postThread = new QThread; 
MakePost *sendPost = new MakePost(); 
sendPost->SetParam(Data, SubUrl, requestString); 

sendPost->moveToThread(postThread); 
sendPost->manager.moveToThread(postThread); 
connect(postThread, SIGNAL(started()), sendPost, SLOT(MakePostSignal())); 
postThread->start(); 

和一個連接槽-stream在主窗口:

connect(SendPost, SIGNAL(SendLog(QString)), this, SLOT(setLogs(QString))); 

線程內部消除一切迎刃而解,如果我在一個線程中運行只收導致qDebug()< < 「GetRes:」 + GetRes;和所有...

請幫助,如何創建線程和GUI之間的信號插槽的連接? 謝謝!

+0

setLogs有兩個參數,但在連接功能中只顯示一個參數。這可能是問題嗎? – Dillydill123

回答

1

網絡請求已在工作線程中異步處理:這就是QNetworkAccessManager所做的。你不需要再添加另一個線程。

對於其他CPU綁定一次性任務,您應該通過QtConcurrent::run利用默認線程池。線程創建和銷燬非常昂貴,線程池具有獨特的定位,可以全面瞭解應用程序對工作線程的需求並最有效地管理其生命週期。對於I/O綁定任務,您應該使用第二個線程隊列作爲第一個參數傳遞給QtConcurrent::run