[Interest] Best way to invoke a slot after some time with QObject::sender

Till Oliver Knoll till.oliver.knoll at gmail.com
Tue Aug 28 11:35:37 CEST 2012


Am 28.08.2012 um 10:22 schrieb Preet <prismatic.project at gmail.com>:

> I couldn't come up
> with a way to tell a potential plugin dev how to 'talk' to my ObjectB
> plugin without directly saying "give your plugin a slot called
> "onSomeSignal()" if you want me to talk to you!"

That's easy: simply *make* the plugins implement a given slot - enforce it! ;)

The tool of choice here is called "interface". C++ doesn't exactly support the notion of "interfaces" such as Java or Objective-C ("protocols") or any other languages which have this feature built in.

But you can easily create the same behaviour with C++ "pure abstract classes" (I guess you must have already have something like this in place anyway).

class MyPluginInterface : public QObject
{
  Q_OBJECT
public:
  virtual void doFoo() = 0; // plugins MUST implement this

public slots:
  void handleBar(Bar *someBar) = 0; // haven't actually tried setting a slot as pure virtual, but should work

  ...
};

(On Windows: don't forget to "DLL export" that interface - Qt offers some nice macros for that in a platform independent manner...)

Off course the above is not exactly "pure", as it inherits from QObject and the Q_OBJECT macro expands to more code etc. But it serves its purpose  to make plugins implement the desired methods and slots.

Then have some "Controller" class ("Plugin Manager") connect the signals from your ObjectB to the slots (which now are guaranteed to be there) of the plugins (when they are loaded, when they become "active" or any other suitable time in their lifecycle).


OR (my preferred way):

Don't enforce that slot and simply tell your plugins: "If you want me to talk to you, connect YOURSELF! Here's the ObjectB signal you're interested in."

That way the plugin is more flexible, because the plugin's logic might know better WHEN to connect (and disconnect).


Also I mentiomed a "handle" object in my previous post. If you want to avoid that every single plugin is informed by ObjectB when something happened ("result is ready, pick it up!" - Plugin: "Oh nice! But wait... the result is not for me - I have a different handle object..."), you could have the handle object emit the signal(s) instead of the ObjectB (which would trigger the signal emission on that particular handle).

So only the plugin having that particular handle would get informed by that signal. Also only the plugin(s) actually waiting for a result would be informed, as the others would have released their handle objects already (and hence be disconnected from any signals).

Makes sense?

Cheers,
  Oliver


More information about the Interest mailing list