views:

105

answers:

4

The Win32 API has a PostMessage function that posts a message to the end of the GUI message queue to be processed later from the GUI thread, as opposed to SendMessage which sends and processes the message synchronous with the calling thread.

Is there a Qt solution for PostMessage functionality? A coworker suggested that Qt's server/socket implementation could provide it; is that a reasonable approach?

+4  A: 

Look at QTimer::singleShot. In your case you'd want to use it with an msec value of 0, which should provide the same functionality. (This is regularly used to implement delayed intialization, until the GUI event loop is running)

jkerian
+7  A: 

Check QCoreApplication::postEvent().

Donotalo
I'm accepting this answer because it closely emulates `PostMessage`, which is what I asked. However, I decided I am going to use jkerian's solution (QTimer::singleShot) because it better fits in with Qt's signals/slots. Thanks to you both!
Jesse Stimpson
+3  A: 

Similar to the QTimer solution, but with the advantage that you can pass arguments, is the QMetaObject::invokeMethod way:

 QString SomeClass::compute(const QString&, int, double);
 ...
 QMetaObject::invokeMethod(obj, "compute", Qt::QueuedConnection,
                       Q_RETURN_ARG(QString, retVal),
                       Q_ARG(QString, "sqrt"),
                       Q_ARG(int, 42),
                       Q_ARG(double, 9.7));

The QueuedConnection queues it in the event loop, DirectConnection would execute it immediately.

Frank
+3  A: 

All answers so far are good, I just want to add that you can also use connect() with Qt::QueuedConnection for the connection type.

Ringding