[Interest] C++ abstract class expose to Qml and property

Jérôme Godbout godboutj at amotus.ca
Fri Feb 12 18:46:20 CET 2021


Hi,

I'm having trouble figuring out what is the best way to do the following:

  1.  I have an C++ abstract class that doesn't inherite QObject with abstract method (class SerializationInterface)
  2.  I want to expose that class to Qml and be able to have SerializationInterface* Q_PROPERTY into some other class.
  3.  The class that implement the SerializationInterface already inherit QObject.

class SerializationInterface
{
public:
    virtual bool serialize(QDataStream& stream) = 0;
    virtual bool deserialize(QDataStream& stream) = 0;
};

class OtherObject : public QObject, public Serializationinterface // Here the QObject is a more complexe QObject inherited class, just to simplify writing for example
{
                Q_OBJECT
public:
                bool serialize(QDataStream& stream) override;
                bool deserialize(QDataStream& stream) override;
};

class ControllerA : public QObject
{
                Q_OBJECT
                Q_PROPERTY(SerializationInterface* obj READ ....)
};

Is this possible? I have test the following so far:

  1.  Q_DECLARE_METATYPE(SerializationInterface*) seem to be impossible since it's not a Q_Object
  2.  Make the a Q_DECLARE_INTERFACE(SerializationInterface, "com.mymodulename") but I cannot use that as Property with only that.
  3.  Adding QML_INTERFACE to SerializationInterface doesn't seem to allow assigning a QObject* that implement the  SerializationInterface to the SerializationInterface* property.
  4.  I cannot call qmlRegisterInterface<SerializationInterface>(...)
  5.  I did try to add Q_DECLARE_METATYPE(SerializationInterface*) after the Q_DECLARE_INTERFACE() now it seem to work either

gaving me this so far but it doesn't work, when try to set in Qml "controllerA.obj = otherObjectInstance" I always end up with : "Error: Cannot assign QObject* to SerializationInterface*"

class SerializationInterface
{
   QML_INTERFACE
public:
    virtual bool serialize(QDataStream& stream) = 0;
    virtual bool deserialize(QDataStream& stream) = 0;
};
Q_DECLARE_INTERFACE(SerializationInterface, "com.mymodulename")
Q_DECLARE_METATYPE(SerializationInterface*)

class OtherObject : public QObject, public Serializationinterface // Here the QObject is a more complexe QObject inherited class, just to simplify writing for example
{
                Q_OBJECT
              Q_INTERFACES(SerializationInterface)
public:
                bool serialize(QDataStream& stream) override;
                bool deserialize(QDataStream& stream) override;
};


How does accomplish this properly? Is it even possible? How do you solved it?
Thanks, regards,

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20210212/19720cab/attachment.html>


More information about the Interest mailing list