Pablo De Luca
Pablo De Luca

Reputation: 823

Q_PROPERTY: MEMBER vs READ/WRITE

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)

Upvotes: 10

Views: 16846

Answers (2)

Libor Tomsik
Libor Tomsik

Reputation: 718

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:

  • MEMBER -> just for QMLs
  • READ, WRITE, NOTIFY -> C++ and QML

If you would like to avoid programming trivial getters and setters, define your own makro wrapping Q_PROPERTY.

Upvotes: 9

skypjack
skypjack

Reputation: 50550

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.

Upvotes: 9

Related Questions