Search code examples
qtprogress-barqthread

How to terminate a thread in Qt C++


I have used QFuture to start a thread for a function that I already had in my code that was taking a long time and freezing my GUI.

The thread seems to be working ok:

QFuture<int> result = QtConcurrent::run(&m_DC, &DatabaseController::getAll);

however when the getAll function ends I think this thread is still running which it shouldn't be, but I don't know how to end or finish it. I've looked at the documentation but it doesn't really make it clear.

Basically I'm showing a progress bar as busy when the thread starts and want to hide it when it ends

if(result.isRunning())
{
    ui->progressBar->setRange(0,0);
    ui->progressBar->show();
}

if(result.isFinished())
{
    ui->progressBar->hide();
}

Solution

  • Using QFutureWatcher to monitor the QFuture returned by QtConcurrent::Run, connect QFutureWatcher::finished to a slot to wrapped the display of your progressBar. Something like

    connect(&job_watcher_,
            SIGNAL(finished()),
            SLOT(endLengthyJob()));
    

    MainWindow.cpp

    void MainWindow::endLengthyJob()
    {
        ui->progress_bar->hide();
    } // end_slot(MainWindow::endLengthyJob)
    

    A side note: Thread spawned by QtConcurrent::Run cannot be terminated.