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

Does a derived class inherit its base class's meta properties, even without QObject?



  • Hello,
    according to this thread QObject derived classes always inherit the Q_PROPERTY() declarations of the base classes.

    However, what about Q_GADGET which is lighter than Q_OBJECT.
    I can't make my class derive from QObject (I need copy semantics e.g.) and therefore I use the Q_GADGET macro instead of Q_OBJECT.
    From my experiment, it seems like now the QML properties aren't inherited. Is there any way on how to inherit the properties or is this an intentional limitation?

    In the end I could also switch to composition instead of inheritance in my case, i.e. use the base class as a member, which then should make the properties available, if I add a single Q_PROPERTY for the member. However, inheriting those properties would be easier for me, so can you guys give me any info on whether this can work?


  • Lifetime Qt Champion

    Hi,

    What are you copying from your custom class ?



  • @SGaist Pretty much the entire class. Its members are mostly primitive types, all available with copy semantics themself.


  • Lifetime Qt Champion

    If you really need your class to be a QObject, then what about implementing a clone function ? You create a new object where you copy all members and you're good to go.



  • @SGaist Not really. I don't think this workaround is suitable to every use case.
    Consider for instance the possibility that I want to insert my class into a std::vector. The vector insert operation always uses copy semantics, so there is no way how I could insert the class into a vector. And afaik move semantics don't work with QObject either.


  • Lifetime Qt Champion

    Use pointers to QObject when using them with QVector.



  • @SGaist What about smart pointers? Is there a way to get a QObject into a std::shared_ptr for instance?

    I am not using the Qt way of parent ownership, because I prefer the smart pointer approach. I think there is no way to std::make_shared a QObject, is there? This would probably require copy semantics somewhere to work.


  • Lifetime Qt Champion

    You would likely have to use std::make_shared.

    But bewarel, you have to take good care of knowing when your objects might get parented (for example putting a widget in a layout) or when ownership is taken by the called class (for example QTableWidget::setCellWidget).

    You are likely going to make your life difficult by wanting to avoid Qt's ownership paradigm while writing a Qt application.



  • Alright, now what about propagating those members to QML.
    If I decide to store pointers to custom classes, would I register the pointer to the class for QML to somehow make QML understand the pointer, or would I rather always dereference the pointer at the last step before propagating it to QML?


Log in to reply