How to implement a user-defined message?
-
Hi,
I am using Qt 4.8.3 to implement a Windows desktop application. Now I need to implement a user-defined message. Then in a thread of the application, I need to send this message the main Qt Window and wait until the message is processed by the main Window, just like the SendMessage function in Windows SDK. How to do this?
Currently I can implement the feature like PostMessage, but what I need is like SendMessage, to wait until the message is processed.
If there is a sample, then that will be great!
Thanks
-
Window Messages are a Microsoft Windows thingy. With Qt you generally would not do this with "native" Window Messages. It's unusual and it would not be portable at all! Instead you use "Signals and Slots":http://qt-project.org/doc/qt-4.8/signalsandslots.html.
Note: What you want here is a "BlockingQueuedConnection":http://qt-project.org/doc/qt-4.8/qt.html#ConnectionType-enum ;-)
Example:
http://pastie.org/9207247 -
[quote author="chcw" date="1400972448"]So if I understand correctly, here signal just works like a message in Windows[/quote]
Well, in a way, yes.
But while Window Messages are transmitted between Windows and they are specific to the Windows operating system, Signals are transmitted between Qt Objects and they are cross-platform. Also a Signal can contain arbitrary parameters, like a function call. It's actually more like a fully-fledged RPC.
Since the concept of "Signals and Slots":http://qt-project.org/doc/qt-4.8/signalsandslots.html is so important for Qt, I really recommend you carefully read the Qt documentation about it!
[quote author="chcw" date="1400972448"]and BlockingQueuedConnection works like a message queue that is synchronous.[/quote]
Well, with a standard (direct) connection, the Slot will be executed immediately and in the same thread that emitted the Signal. But with a queued connection, the Slot will be executed in the thread to which the receiver object belongs. So if the "background" thread sends a queued signal to the "main" dialog (which belongs to the "main" thread), then the Slot is executed in the context of the "main" thread. Note, however, that using queued connections requires that the receiving thread runs an event loop - similar to a "message pump" in native Windows applications. Last but not least, a blocking queued connection works exactly like a queued one, except that the thread which emits the signal will be blocked until the receiving thread has actually processed the signal.