tags:

views:

574

answers:

4

In Qt an object belongs to the thread on which it has been created. We need to access controls created in main thread from background thread. However as soon as we refer the object, application goes into hang state. Please let me know how to access and modify controls in the different thread which hasn't created the controls.

Thanks in advance.

A: 

Try to pass the class pointer on the constructor

jose
+1  A: 

You can fire a signal from the background thread to be executed in a slot on the main thread. If I remember correctly, this is done automatically if you specify Qt::AutoConnection in the connect call.

OregonGhost
+1  A: 

You will have problems accessing many of the Qt-specific portions of code from one thread for an object that is owned by a different thread. The easiest way around this is to use signals and slots, as suggested by OregonGhost. If that doesn't suffice, you should look at the event code. You could send an event to object A which contains a pointer to object B (that should receive the response), and then in the customEvent() function of object A, create an event for the response and post it to object B. The cusotmEvent() function is always run in the thread that owns the given object, so you are safe to interact with the Qt-provided code as much as you want at that point. Posting events to another object is also specifically listed as being thread-safe, no matter the owning thread of the receiving object.

Caleb Huitt - cjhuitt
+1  A: 

Well I can't agree. Qt says clearly that you can't access gui from other thread than main. There are two ways of achieving what you need.

  1. make Qt::QueuedConnection between your thread and main window i.e. main window slot updateProgressBar(int), thread signal updateProgressBar(int). you make connection like this connect(workerThread, SIGNAL(updateProgressBar(int)), mainWindow, SLOT(updateProgressBar(int)), Qt::QueuedConnection) You can also connect your worker thread signals directly to widgets you want to update
  2. Define your own custom events (your custom event type value must be >= QEvent::User and <= QEvent::MaxUser) , reimplement customEvent in main window and handle properly those events. Pass events to your main window (you need then pointer to your main window object) by QCoreApplication::postEvent(mainWindow, yourCustomEvent)
Kamil Klimek