Private QObject API

From Qt Wiki
Jump to: navigation, search

There are certain QObject macros and conventions that are for use in private Qt APIs only. This page describes them.


Introduced here.

This macro is used when you have a C++ class that is public that exposes a property whose type is not public. For example, QQuickItem is a public C++ class that exposes an anchors property, whose type is the private QQuickAnchors class:

   Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQuickAnchors * anchors READ anchors DESIGNABLE false CONSTANT FINAL)

In this case, the macro expects there to be a getter named anchors() in the type returned by QQuickItem::d_func(), which there is:

   QQuickAnchors *anchors() const;

When using this macro, it's necessary to include the generated moc file at the end of the corresponding .cpp file:

   // ...
   #include "moc_qquickitem_p.cpp"

If you don't do this, you may see an error like the following (example taken from another class -- replace popup with item and it's the same error):

   [...] moc_qquickpopup_p.cpp
   .moc\debug\moc_qquickpopup_p.cpp(1069): error C2027: use of undefined type 'QQuickPopupPrivate'
   c:\dev\qt5-dev-d\qtquickcontrols2\src\quicktemplates2\.moc\debug\../../../../../../qt5-dev/qtquickcontrols2/src/quicktemplates2/qquickpopup_p.h(71): note: see declaration of 'QQuickPopupPrivate'
   .moc\debug\moc_qquickpopup_p.cpp(1069): error C2227: left of '->anchors' must point to class/struct/union/generic type


Similar to Q_PRIVATE_PROPERTY, Q_PRIVATE_SLOT is used when you have a slot in a private class that you want to be considered part of the API of the corresponding public class, without affecting the interface (and hence binary compatibility) of that public class. Using QQuickItem as an example again, Q_PRIVATE_SLOT is used to declare this private slot in qquickitem.h:

       Q_PRIVATE_SLOT(d_func(), void _q_resourceObjectDeleted(QObject *))

The slot itself is declared in qquickitem_p.h:

   void _q_resourceObjectDeleted(QObject *);