O
O
Oleg Seledets2018-12-05 09:42:32
Qt
Oleg Seledets, 2018-12-05 09:42:32

How to correctly send a function to a thread?

Hello.
there is a simple function for example:

spoiler
void MainW::foo(){
    if(ui->progressBar->value()<50){
        ui->progressBar->setValue(79);
    }
    else{
        ui->progressBar->setValue(23);
    }
}

Also trying to put it in another thread:
spoiler
void MainW::on_output_excel_butt_clicked()
{
    QThread trd;
    moveToThread(&trd);
    connect(&trd, SIGNAL(started()), this, SLOT(foo()));
    trd.start();
}

The app just closes when the button is clicked, no errors. what could be the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly, 2018-12-05
@oleja1ee7

Just in case, I'll leave this code here. As I understand it, this is what you want to get: a function in a separate thread, without blocking the GUI + you need to wait for the execution results.

QEventLoop loop;
QFutureWatcher watcher = QConcurrent::run(someFunc);
connect(&watcher, &QFutureWatcher::finished,  &loop, &QEventLoop::quit);
loop.exec();
auto result = watcher.result();

If the result of the execution is not needed, then the function can simply be run asynchronously with one run method.

A
Antony, 2018-12-05
@RiseOfDeath

EMNIP in Qt can only work with GUIs in the main thread. Those. some "heavy" or blocking actions should be done in a separate thread, and then, through signals, pull the functions in the main thread so that they change the state of the guys.

A
Alexander Ananiev, 2018-12-05
@SaNNy32

Try this option

connect(&trd, SIGNAL(started()), this, SLOT(foo()), Qt::QueuedConnection);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question