开发者

Accessing Qt widget from different thread

In Qt an object belongs to the thread on which it has been created. We need to access controls created in main thread from ba开发者_运维问答ckground 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.


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)


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.


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.


Try to pass the class pointer to the constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜