Hunk
Hunk

Reputation: 485

Update QT Graphicview from other Thread

i am at the moment really confused about threading in QT. I read so much different opinions which i can realize this.

I have a class (Computations) which do heavy computations and generate a lot of solution. When this class find a solution i call with help of

boost::function<void (Solution)> f;

a custom function. Which can be bind with

f = boost::bind( &MainWindow::FoundSolution, this,_1);

No i have my mainwindow in QT. There i call my class Computations with

Computations comp(f); 
QFuture<void> future = QtConcurrent::run(comp,&Computations::DoSomethink);

So it compute while i can use the GUI and i get the response of new solutions to the FoundSolution function in my mainwindow. In this function I use QGraphicview to draw my solution. The Qgraphicsview is a member of my Mainwindow.

This works sometimes.

But i often get the following error

Assert failure in QCOREApplication::SendEvent: " cannot send events to objects owend by a different thread. Current thread 438bc40. Receiver " (of type "Qgraphicsscene) was created in thread 15dcc00, file kernel\qcoreapllication line 494

This mean i call my GUI application from a thread which is not the main and this is forbidden by QT. But with my boost bind i should be in my main thread or? And why it works sometimes ?

Do you know a better implementation for this? I am really new with QT and threads.

Thank you for your help.

Upvotes: 2

Views: 628

Answers (3)

m. c.
m. c.

Reputation: 895

 connect( &sender, SIGNAL(), &receiver, SLOT(), Qt::QueuedConnection)

The easier fix is to add Qt::QueuedConnection to the problematic slot connection call.

Upvotes: 0

nbilal
nbilal

Reputation: 1099

If you emit a signal from you worker thread that is connected to a slot of an object that lives in the ui thread, the slot will be executed in the ui thread.

So basically if you want to draw a new point in the QGraphicsView, send a signal from your worker thread passing in the coordinates of the new point to draw. The signal need to be connected to an object that lives in the ui thread. The slot will then handle drawing the new point in the QGraphicsView which will work since the slot is executed in the ui thread.

For more information see Signals and Slots Across Threads

Upvotes: 2

bjoernz
bjoernz

Reputation: 3852

The normal way to do this is to use signals and slots. You can find some documentation, which is specific to your problem, here: Qt 4.8, Qt 5.

Upvotes: 0

Related Questions