Important: Please read the Qt Code of Conduct -

Best way to display a list of polymorphic objects

  • Hello, all. I'm working on a project where I've got a list of objects that I need to display. The list exists as a property on a QObject in C++. A simplified example of what I'm trying to do would be something like a ParkingGarage class which inherits QObject and exposes a list of cars as a property, where there are various types of cars including SportsCar, Minivan, PickupTruck, etc. and each of these will ultimately be rendered differently, but all in a single ListView. Furthermore, all car types share some methods, such as lock() and unlock() and properties like color, but others are specific to a type such as PickupTruck::openTailgate(). Ideally, these type-specific semantics would be visible in QML.

    Because I'm implementing this from scratch, I have a lot of flexibility in how I do this, and I'm trying to determine the best way. For instance, should the various types of car be Q_OBJECTs or Q_GADGETs? Should they all implement a common interface, or be free standing classes? Is it best to use a QList based model, a QQmlListProperty or a QAbstractItemModel or something else (I'd like to have transition animations on list modifications, so is QAbstractItemModel my only option?)? Alterations to this list may originate from C++ or javascript (if necessary, I can proxy the javascript updates through calls to C++ though).

    I've played around with ListViews in the past, but this is the first time I've been trying to display a list of items of heterogeneous types, and I'm not sure how best to proceed. Advice is greatly appreciated. :)

Log in to reply