3

I've stumbled across a problem I can't solve on an elegant way right now. The situation: I have a callback function which is called from outside my application. The callback function has to update some gui object.. Since I can't call (for example) repaint() from within another thread, I have to finde some way to add a function call to the main event loop so the task gets executed at some time.

One possible way would be to use this:

QMetaObject::invokeMethod(object, "functionName", Qt::QueuedConnection, Q_ARG(float, value)); 

However, this just gives me the response that no such Method "Object::functionName". (which is obviously a lie!)

I've also read about connecting a signal to a slot which will be called from the event loop by setting the connection type to Qt::QueuedConnection. However, using QOjbect.:connect() won't work since I don't knwo which object the signal needs to get. Nice would be something like

QObject::emit(object, SIGNAL(function(flaot)), arg);

ruhig brauner
  • 943
  • 1
  • 13
  • 35
  • usually `QMetaObject::invokeMethod` works fine. it also does not lie, if you have a typo in your call, it will fail (because it is evaluated at runtime - without the compiler checking if the function exists) and output that message. check your call and it should work – Zaiborg Nov 12 '14 at 08:28

1 Answers1

3

QMetaObject::invokeMethod is usually what you should use in this kind of situation. Make sure that:

  • object is a QObject subclass with the Q_OBJECT macro at the top
  • functionName is either declared in the slots section or has the Q_INVOKABLE macro
jturcotte
  • 1,273
  • 9
  • 9
  • Hi, declaring it as a slot helped. Somehow missed this. Thanks! And there is no "faster" way? The application is quite performance-oriantated (real time audio etc.) and I would like to save cpu time where possible. :) – ruhig brauner Nov 11 '14 at 23:20
  • 1
    I'm not aware of any, AFAIK posting a custom QEvent or using a 0ms QBasicTimer aren't possible across threads. InvokeMethod has quite an overhead so what I've been relying in the past is to batch the invokes into as few messages as possible, where I process all the accumulated data protected by a QMutex or QSemaphore. – jturcotte Nov 12 '14 at 08:10