简体   繁体   中英

Qt C ++ emit from the thread, in the slot GUI

There is a slot in the main mainwindow class(GUI), which displays data in QTextBrowser:

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

There is a class that runs in a separate thread, making POST-search and to insert the data in 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);
}

The call thread:

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();

and a connect slot-stream in mainwindow:

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

whithout thread all work out fine, if I run in thread received only result qDebug () << "GetRes:" + GetRes; and all ...

Please help, how to create a connect of signal-slot between the thread and GUI? Thanks!

The network requests are already handled asynchronously in a worker thread: that's what QNetworkAccessManager does. You don't need to add yet another thread into the mix.

For other CPU-bound one-off tasks, you should leverage the default thread pool via QtConcurrent::run . Thread creation and destruction is expensive, and the thread pool is uniquely positioned to have a global knowledge of your application's need for worker threads and manage their lifetimes most efficiently. For I/O-bound tasks you should use a second thread queue that's passed as the first argument to QtConcurrent::run .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM