0

I am trying to write a wrapper to some data that will be held in a container. This data is going to be interfacing with QML, and henceforth will have Q_PROPERTIES in it. However, I want this data to be derived from a specific base class, so I can call overridden methods without having to cast. Here is an example.

class Base : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int value READ value WRITE setValue NOTIFY valueChanged)

public:
    /*implementation is irrelevant, just boilerplate code*/
}

class BaseBool : public Base {
    Q_PROPERTY(bool value READ value WRITE setValue NOTIFY valueChanged)

public:
        /*I want to override the functions here so I can just call them
        like I would for a base class, but I want them to be different types.
        I want to extend this for other types too.*/
}

Hopefully this makes sense. Obviously something templating the class and have a Q_PROPERTY of type T would be ideal, however that is not possible with current Qt. Are there any decent solutions for this? There might be better design patterns that address this, but I am at a loss right now.

albyhouse
  • 29
  • 2
  • is this what you are looking for? (https://stackoverflow.com/questions/29683341/how-to-override-a-q-property) – Amfasis Oct 18 '18 at 14:33
  • Another solution might be [QVariantMap](http://doc.qt.io/qt-5/qtqml-cppintegration-data.html#qvariantlist-and-qvariantmap-to-javascript-array-and-object) – Amfasis Oct 18 '18 at 14:40
  • @Amfasis - I saw that but doesn't truly do what I want. I want a generic way to reference a "value" from an object and it's derived classes. I want to call Base.getValue() and get returned a bool, int, etc. I realize this is kind of finnicky with Qt since I cannot templatize a QObject class. However, I think I settled on a QVariant type of solution to wrap my values. – albyhouse Oct 18 '18 at 16:26
  • but it is not allowed to have different return values from C++ (https://stackoverflow.com/questions/8967303/override-a-member-function-with-different-return-type). However, IIRC you can override the Q_PROPERTY's, where you specify a different READ function (e.g. for `BASE` : `READ valueInt` and for `BaseBool` : `READ valueBool` – Amfasis Oct 19 '18 at 07:51
  • I fail to see a proper use case for this. C++ is typed, in what context would you use the `getValue` function on a baseclass pointer while the return type is depending on the derived class ? – ymoreau Oct 22 '18 at 15:02

1 Answers1

0

All of Qt's metadata can be generated at runtime, or using the C++ compiler and not moc. These properties can be synthesized on the fly or during compilation, and won't be a problem for a templated class. What you're looking for is Verdigris. As long as you have a modern enough compiler, then Verdigris is all you need:

[You] Need a compiler that can do C++14 relaxed constexpr such as GCC 5.1 or Clang 3.5, or MSVC 2017

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313