PDA

View Full Version : Q_PROPERTY Code Generation



lexfridman
16th January 2011, 19:57
I am using the Q_PROPERTY macro as described here:
http://doc.qt.nokia.com/4.7-snapshot/properties.html

Let's consider this macro declaration:
Q_PROPERTY(int foo READ getFoo WRITE setFoo)

Now I am required to define a function getFoo() and setFoo(int):

int getFoo() { return foo; }
void setFoo(int x) { foo = x; }

Is there a way to automatically generate these two functions? The reason I ask is I would like to define 20-30 Q_PROPERTY macros for each of the parameters that control a simulation system I coded up, and I never need to define a read or write function that's more complicated than the ones above.

My only option right now is to write a Perl script to perform this code generation, but I was hoping there was an elegant way using Qt to specify "default functions" of this kind.

Thanks.

javimoya
16th January 2011, 21:09
Sadly... you must write the getter and setter... :(

in Objetive C you don't need...

I don't know why Qt don't implement that.

hickscorp
27th July 2011, 03:54
Why not making a macro?

#define Q_PROPERTY_WITH_ACCESSORS(name, type, getter, setter) private: type _##name; public: Q_PROPERTY(type name READ getter WRITE setter) type const& getter () const { return _##name; } void setter (type const &v) { _##name = v; }

This macro will take 4 arguments:
- Property's name,
- Property's type,
- Getter name,
- Setter name.

For example, you can call it where you would call Q_PROPERTY like that:
Q_PROPERTY_WITH_ACCESSORS(toto, QString, toto, setToto)
It will generate a property named "toto" of type QString, reader "toto", setter "setToto", private member named "_toto".

i did not test what would be the moc'ing result of that (Does MOC expands macros before processing?...) as i just invented it.

Pierre.

sebas951
15th January 2014, 20:43
Asuming you have your private members, and you want public getters and setters :


private :
QString member1;
QString member2;
]

right click on your member's name, in this case member 1 and/or member 2 (one at the time), then Refactor->Create Getters and Setters
that will do it ;)

anda_skoa
16th January 2014, 09:37
Well, this thread is three years old and Qt5 didn't exist back then, but there is a new variant of the macro now that can generate the getter and setter



Q_PROPERTY(QColor color MEMBER m_color NOTIFY colorChanged)
Q_PROPERTY(qreal spacing MEMBER m_spacing NOTIFY spacingChanged)
Q_PROPERTY(QString text MEMBER m_text NOTIFY textChanged)
...
signals:
void colorChanged();
void spacingChanged();
void textChanged(const QString &newText);

private:
QColor m_color;
qreal m_spacing;
QString m_text;


Cheers,
_