4

I have the following code which implements QtConcurrent::run() with QFutureWatcher to start the fetch() function which runs a shell process. Upon completion, I want to call the writeDesc function, but it never gets called.

void MyClass::on_fetchButton_clicked()
{
    QFuture<void> fetcher;
    QFutureWatcher<void> watcher;
    connect(&watcher, SIGNAL(finished()), this, SLOT(writeDesc()));
    fetcher = QtConcurrent::run(this, &MyClass::fetch);
    watcher.setFuture(fetcher);
}

void MyClass::fetch()
{
    [...]
    qDebug()<<"Thread done";
}

void MyClass::writeDesc()
{
    qDebug()<<"Slot called";
    [...]
}

fetch() works fine but the program shows only the debug message Thread done and not Slot called. Why isn't writeDesc being called?

Aakash Jain
  • 1,963
  • 17
  • 29
  • 1
    Reminder: questions with problems caused by an automatic variable getting destroyed at the end of a function are subject to closure. They are in the "simple typo" category. OTOH, it's true that Qt could offer a qWarning in destructors of some classes that are especially prone to such misuse. – Kuba hasn't forgotten Monica Mar 22 '14 at 14:29

1 Answers1

6

The problem is that the watcher object is destroyed when leaving the MyClass::on_fetchButton_clicked() method. A destroyed object can not emit something. Try to allocate and connect the watcher in the constructor of your class. Don't forget to destroy in the destructor.

Silicomancer
  • 8,604
  • 10
  • 63
  • 130