CloseEvent and QtConcurrent
-
Hi,
I have problems when I quit my application.
In this app, i launch a thread which run while true like this:@flag= true;
QtConcurrent::run(this,&MonWidget::maFonction);@I keep a flag in order to stop my thread as i want.
@void MonWidget::maFonction()
{
while(1)
{
"Différent traitement"if(!flag) return;
}
}@When i close my widget ("MonWidget"), two choices are possible, the first one, which use a slot, works each time:
@void MonWidget::back()
{
flag = false;
this->parentWidget()->show();
this->deleteLater();
}@The other choice when I click on the red mark :
@void MonWidget::closeEvent(QCloseEvent *e)
{
flag= false;
e->accept();
}
@This second choice doen't work, the app don't close with the status 0.
I don't understand why the second methode don't work.Thanks for your help.
M. FURIC
-
Hi,
That's because your application quits before your thread has the chance to shut down.
But anyway, you shouldn't try to run a widget function in a different thread. QWidget is not thread-safe. What does MonWidget::maFonction() do?
-
Hi,
My thread build an image to show.
I have a QpushButon which allow to run/stop as I want and it works properly even though I stop an run many times per second.
The probleme appears when I quit (close/destroy) the widget.
Obviously I stop My thread before i close my widget.
I added a QThread::msleep(100) after the function which stop my thread ans it seems to work. But it's not very clean.Do you have an idea to remove this sleep?
Thx for your help.
-
You need to somehow make sure you don't call QCloseEvent::accept() before your thread has finished. You can call QFuture::waitForFinished() to block your main thread until the thread finishes.
But, I repeat, it is bad practice to run a widget's function in a separate thread, because it becomes very easy to make mistakes.
After you have built the image, how do you transfer the image data back to the main thread for rendering?
-
Hi,
Building the image in a different thread is fine, but only the copy bit is not thread safe. You might get memory mixup between writing and reading between threads. Use signal/slots to pass the image to the GUI thread or use a mutex to protect both the threads from memory corruption. BTW what JKSH says is not completely right. IMOH it's totally forbidden to use two threads for GUI operations. It's stated clearly in the Qt docs! Just don't, even if it works!! -
Hi, Jeroentje.
My problème is not in the thread , I use mutex and without it it's works fine.
I have a button to run/stop my thread and the thread works fine.
My problème is when i close my app with the red cross when my thread running. I think Qt treat the QcloseEvent before to stop my thread.