Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Get instance of the "attacher" in an attached object.



  • I have an attached properties object declared thusly:

    QML_DECLARE_TYPEINFO(QAttacher, QML_HAS_ATTACHED_PROPERTIES)
    // ...
    static QAttachee *QAttacher::qmlAttachedProperties(QObject *object)
    {
        return new QAttachee(object);
    }
    

    Within the scope of the QAttachee, how do I receive the instance of it's parenting QAttacher?


  • Moderators

    Isn't that the object parameter you're getting in this function?



  • No sir. Implemented in QML, assuming the QML type is registered with the same type names used above, you would have something like this:

    QAttacher
    {
        id: attacher
    
        Item
        {
            id: attachee
    
            QAttacher.property: some_value
        }
    }
    

    Attached properties are provided to children of QAttacher, in our case the Item with id: attachee, which is what the object parameter points to. A call to object->metaObject()->className() will simply yield QQuickItem.

    What I want to know is how to get the pointer to the QAttacher with id: attacher. How do I retrieve this information?


  • Qt Champions 2018

    There is no attacher instance from the QML engine perspective, only an attaching type. Your code would work the same without your outer attacher.
    To be able to reference the outer parent in one of your attached object, you could simply check the parent object of the attachee. Alternatively force the creation of the attached object from c++ ( with https://doc.qt.io/qt-5/qqmlengine.html#qmlAttachedPropertiesObject) when you add an item in the default list property of your QAttacher, you could then call a setter on it and pass your QAttacher instance to it, and potentially do some more initialization.



  • @GrecKo Thank you for this clarification and alternative approach, marked as solved.


Log in to reply