<mysterious but solved> Trouble using qobject_cast with const QObject*



  • I am using Q_DECLARE_INTERFACE / Q_INTERFACES in order to be able to use qobject_cast for objects which are not QObjects. The following works fine:

    @class ITsc_SnapEnabledContainer
    {

    public:
    // Some pure virtual methods that don't matter here

    // Helper to cast QObject to this interface
    static ITsc_SnapEnabledContainer* castToSnapEnabledContainer(QObject* pObject);
    

    };

    Q_DECLARE_INTERFACE(ITsc_SnapEnabledContainer, "ITsc_SnapEnabledContainer")@

    ...and in the cpp:

    @ITsc_SnapEnabledContainer* ITsc_SnapEnabledContainer::castToSnapEnabledContainer(QObject* pObject)
    {
    return qobject_cast<ITsc_SnapEnabledContainer*>(pObject);
    }@

    I have been using these types of cast operations for a long time, and never had any trouble.
    Until I tried to add this code:

    Header:
    @
    // Const overload
    static const ITsc_SnapEnabledContainer* castToSnapEnabledContainer(const QObject* pObject);
    @

    cpp:
    @
    const ITsc_SnapEnabledContainer* ITsc_SnapEnabledContainer::castToSnapEnabledContainer(const QObject* pObject)
    {
    return qobject_cast<const ITsc_SnapEnabledContainer*>(pObject);
    }
    @

    As soon as I add this, I get errors:
    @Error 1 error C2039: 'qt_check_for_QOBJECT_macro' : is not a member of 'ITsc_SnapEnabledContainer' c:\qtvs2010\4.8.1\src\corelib\kernel\qobject.h 368
    Error 2 error C2039: 'staticMetaObject' : is not a member of 'ITsc_SnapEnabledContainer' c:\qtvs2010\4.8.1\src\corelib\kernel\qobject.h 370
    Error 3 error C2228: left of '.cast' must have class/struct/union c:\qtvs2010\4.8.1\src\corelib\kernel\qobject.h 370
    @

    Any ideas?



  • Add Q_OBJECT macro in your class (don't forget to run qmake), qobject_cast needs that macro, see the documentation "here":http://qt-project.org/doc/qt-5/qobject.html#qobject_cast



  • In this case, it is not a QObject-derived class. The qobject_cast should work based on the Q_DECLARE_INTERFACE / Q_INTERFACES macros.

    See "docs on qobject_cast":http://qt-project.org/doc/qt-4.8/qobject.html#qobject_cast

    "qobject_cast() can also be used in conjunction with interfaces; see the Plug & Paint example for details."



  • The following works, but I wonder why:

    @const ITsc_SnapEnabledContainer* ITsc_SnapEnabledContainer::castToSnapEnabledContainer(const QObject* pObject)
    {
    return qobject_cast<ITsc_SnapEnabledContainer*>(pObject);
    }@

    It looks like I can take a const-QObject, make a non-const qobject_cast to return a const interface. Strange.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.