简体   繁体   中英

Qt Concurrent with signals & slots

I'm a novice in threads and someone advises me to use Qt Concurrent (Qt C++).

I'm trying to run a function in a thread by using Qt Concurrent, my functions runs well but my signal/slot is never emitted.

However for your information if I launch my function without using thread everything works fine.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QFutureWatcher<void> *watcher1 = new QFutureWatcher<void>();
    connect(watcher1, SIGNAL(finished()), this, SLOT(getSizeFinished()));

    QString string = "http://ipv4.download.thinkbroadband.com/50MB.zip";
    QFuture<void> future1 = QtConcurrent::run(this, &MainWindow::getRemoteFileSize, string);
    watcher1->setFuture(future1);
}

void MainWindow::getSizeFinished()
{
       qDebug() << "--- FINISHED ---";
}

void MainWindow::getRemoteFileSize(const QString &url)
{
    qDebug() << "Function - getRemoteFileSize";
    QNetworkRequest req;
    m_netmanager = new QNetworkAccessManager();
    req.setUrl(QUrl(url));
    m_reply = m_netmanager->get(req);
    connect(m_reply, SIGNAL(metaDataChanged()), this, SLOT(remoteHTTPHeader()));
}

void MainWindow::remoteHTTPHeader()
{
    qDebug() << "Function - remoteHTTPHeader";
    remoteSize = m_reply->header(QNetworkRequest::ContentLengthHeader).toInt();
    qDebug() << "Remote File Size: " << remoteSize;
    m_reply->deleteLater();
    m_netmanager->deleteLater();
    qDebug() << "SIZE " << remoteSize;
}

You probably don't need to create a connection in this case, you could call MainWindow::remoteHTTPHeader() right after m_reply = m_netmanager->get(req); .

You might want to check if the reply is effectively finished like so:

if (m_reply->isFinished()) {
    remoteHTTPHeader();
} else {
    connect(m_reply, &QNetworkReply::finished, this, &MainWindow::remoteHTTPHeader);
}

This way you handle both fast and slow connections. Also notice how I created the connection using function pointers instead of SIGNAL and SLOT macro, this syntax is better since it checks at compile time if the functions exist so you avoid making typos and the like.

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