What is the purpose of attached properties in QML?

  • In the QT help document, it is said that the attached properties allows users to extend existing objects with additional attributes. However, if we want to do so, why not we just derive a C++ class, add new Q_PROPERTY properties and then register it as a new QML type?

    For instance, in the BirthdayParty example, attached property "QDate rsvp" in the BirthdayPartyAttached class can actually be added directly in the BirthdayParty class. I did not see any sense of declare an additional class to extend the BirthdayParty QML type.

    Maybe I am wrong, can anyone give an in-depth explanation?

  • ListView is a good example. It allows any Item type as a delegate. You can use Rectangles, Images, Rows, MouseAreas, Buttons, anything you wish. By using the attached property mechanism, ListView is able to provide ListView and delegate instance specific properties for the delegates, regardless of their exact type.

    If subclassing had been used to provide this information, you would be only able to use a dedicated ListViewItem type and you would always have to add your content as children of the extra wrapper items. It would be an annoying limitation API-wise, and it would cause unnecessary overhead by creating deeper item-hierarchy.

Log in to reply