I was reading the documentation of Qt 5.5 about Q_PROPERTY macro, but I can't understand it well enought.
I understand that you can use in this macro with the keyword MEMBER or the accessors READ/WRITE instead. If you use keyword MEMBER you don't have to write the accessors, because you can access to your private data member (the property) with the use of setProperty() and Property(), like a set and get.
The point is: is there any difference between using MEMBER and using READ/WRITE? when should you use one and when the other way?
For if necessary:
Example of using MEMBER:
Q_PROPERTY(QString text MEMBER m_text NOTIFY textChanged)
Example of using READ/WRITE:
Q_PROPERTY(int propX READ getX WRITE setX)
Exposing Properties. A property can be specified for any QObject-derived class using the Q_PROPERTY() macro. A property is a class data member with an associated read function and optional write function. All properties of a QObject-derived or Q_GADGET class are accessible from QML.
The property type can be any type supported by QVariant, or it can be a user-defined type. In this example, class QDate is considered to be a user-defined type. Q_PROPERTY(QDate date READ getDate WRITE setDate) Because QDate is user-defined, you must include the <QDate> header file with the property declaration.
By reading carefully the documentation, it seems to me that there are slightly, important differences.
First of all:
A MEMBER variable association is required if no READ accessor function is specified. This makes the given member variable readable and writable without the need of creating READ and WRITE accessor functions.
That means that you can either use MEMBER
and rely on auto generated, trivial accessor functions or define for yourself those functions if they happen to be more complex than a defaulted one.
In other terms, if your accessor functions are all the way the same, as an example:
int propName() const { return prop; }
Thus, MEMBER
is fine. It does not if you have something like:
int propName() const { return superComplexMathUsedToComputeProp(); }
Also, note that:
The READ, WRITE, and RESET functions can be inherited. They can also be virtual.
If you are dealing with a hierarchy, maybe you want them to be inherited, so maybe to go with READ
and WRITE
would be better.
Which is the best and what to use depends on the specific problem.
The MEMBER creates just ReadProperty and WriteProperty features in qt meta object system(see the generated moc file). This is useful for interfacing with QMLs. In order to use property in c++, the getters and setters has to be implemented as well.
So:
If you would like to avoid programming trivial getters and setters, define your own makro wrapping Q_PROPERTY.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With