[Interest] What's the purpose of Q_DECLARE_INTERFACE?

Elvis Stansvik elvstone at gmail.com
Wed Sep 13 09:26:34 CEST 2017


I'm reading about extending applications with Qt plugins.

What is the purpose of the Q_DECLARE_INTERFACE/Q_INTERFACES mechanism?

The docs says:

    "This macro associates the given Identifier (a string literal) to
the interface class called ClassName." [1]

and

    "Use the Q_DECLARE_INTERFACE() macro to tell Qt's meta-object
system about the interface." [2]

The Plugins wiki page also has some more info [3]:

    "Q_DECLARE_INTERFACE is a macro that defines helper functions that
make qobject_cast<Tool*>(hammer) return a Tool pointer. qobject_cast
is just a template function and you can think of Q_DECLARE_INTERFACE
providing a template specialization for the interface. The macro
itself just expands as a call to qt_metacast that moc generated above.
So, Q_DECLARE_INTEFACE defines qobject_cast<Tool *>(object) which is a
template specialization that translates to
object->qt_metacall("in.forwardbias.tool/1.0");"

(and also some info about the Q_INTERFACES macro: "When moc runs on
the hammer.h code, it inspects Q_INTERFACES. It generates code for a
function called qt_metacall - void *Hammer::qt_metacast(const char
*iname). This goal of this 'casting' function is to return a pointer
to an interface depending on iname. moc also verifies whether the
interface names that you have put inside Q_INTERFACES have indeed been
declared. It can do this by inspecting the header files and looking
for a Q_DECLARE_INTERFACE.")

So from that I gather that the purpose of the mechanism is to make
qobject_cast<SomeInterface*>(..) work, despite SomeInterface not being
a QObject?

But none of the docs explain why this is needed. What is this featured
used for within Qt? Or is it provided for me as an application
developer? If so, when would I use it?

Sorry if the question is dumb, but I think all the docs explain what
the macros do, not why you would want that or why it is needed.

And a related question: Can I use Q_DECLARE_INTERFACE on a class that
is not actually an interface, a class that does not have 100% pure
virtual member functions? E.g. if I want some base functionality in my
plugin "interface" class? (I realize of course that my plugins would
then have to link against the lib that provides this "interface", so
it would be a tighter coupling than just a shared header, but
nonetheless).

Thanks in advance,
Elvis

[1] http://doc.qt.io/qt-5/qtplugin.html#Q_DECLARE_INTERFACE
[2] http://doc.qt.io/qt-5/plugins-howto.html#the-low-level-api-extending-qt-applications
[3] https://wiki.qt.io/Plugins



More information about the Interest mailing list