Can the moc automatically generate getter, setter, and notify methods for properties?
-
I'm wondering if it's possible for Qt's moc / qmake to automatically generate getter, setter, and notify methods for properties? In theory it should be quite easy, as a basic getter / read method just returns the value of the property and a basic setter / write method just sets the value and emits the signal notifying that the value has changed.
This would allow developers to save themselves a whole lot of boilerplate code that clutters up source files.
Note that I'm aware it's possible to generate getter and setter methods using Qt Creator's refactor features, but that's not what I'm talking about. I'm hoping there's a way to add these methods in the files produced by qmake so that there's no reason for the boilerplate code to be in my source files at all.
I found this old thread a little while ago that suggests this is possible starting with Qt5 if you just specify a member variable and a notify signal using Q_PROPERTY:
http://www.qtcentre.org/threads/37845-Q_PROPERTY-Code-Generation
...but I tried it out and it doesn't work -- no getter or setter methods are generated.I also found the same feature request on the bug tracker:
https://bugreports.qt.io/browse/QTBUG-16852
...which suggests the feature is in, but it looks like they consider using MEMBER in Q_PROPERTY sufficient, and while it does avoid the need for getters and setters in some cases, it's not the same thing. Simply assigning to the member variable will not trigger the notify signal to be emitted unless you write getters and setters, and now we're back to having boilerplate code.Is this feature actually in Qt? If not, is there any good or clever way to accomplish it? I have a lot of objects that have a lot of properties, and most of them it's important that they have a notify signal. It'd would simplify my code and workflow immensely if this could be done.
-
@Guy-Gizmo
No, not to my knowledge.Q_PROPERTY
only registers the property with the meta-object system and doesn't in fact generate the methods.while it does avoid the need for getters and setters in some cases, it's not the same thing.
It in fact is very different, since it breaks the encapsulation principle in OOP.
Is this feature actually in Qt? If not, is there any good or clever way to accomplish it? I have a lot of objects that have a lot of properties, and most of them it's important that they have a notify signal. It'd would simplify my code and workflow immensely if this could be done.
You can always put a few macros to write the code for you. I don't consider it a very good practice, but it has been done and it's usable.
Kind regards.