Despite some searchs, I wasn't able to find a way to auto-generate getters and setters for a C++ class, using QT Creator 2.3.1. Would you guys know some way to do so ?
4 Answers
Do a right click on your member then Refactor
then Generate Getter and Setter member function
and you're done :)
On Qt Creator 3.2.x, create the member, then click on it and press alt+Enter :
-
That looks like what I want :) but a refactor only offer me to rename the field. I'm using QT Creator 2.3.1, is that why ? Or is there something to do in the settings ?– meroursNov 1, 2013 at 15:06
-
2@fxm well, I'm running 2.8.1, it might come from the gap between the two versions. I'll take a look, but maybe you should think about an update Nov 1, 2013 at 15:10
-
Updating right now, didn't think there would be such a gap in the repository. Thanks for your answer anyway !– meroursNov 1, 2013 at 15:12
-
It look to me there is no such option in Qt creator 3.2.1, if there is some other way, please let me know– KahnOct 29, 2014 at 11:04
Position your text cursor at the member variable in class definition, then hit Alt+Enter.
-
This doesn't work for me, running Qt Creator under Ubuntu 14 in a VirtualBox. Apr 27, 2018 at 13:48
For me, right-click, Refactor, Create Getter and Setter member functions works, except when the member is a bool.
-
i guess it is not very convenient when you change the property name Sep 29, 2021 at 21:05
Using macro, one can create getter, setter and signal together as follow :
#define GETSET(type, var) \
protected: \
type m##var; \
public: \
type Get##var() const \
{\
return m##var; \
}\
void Set##var(type iVal) \
{\
m##var = iVal; \
var##Changed(iVal); \
}
and calling the macro :
class Student : QObject
{
Q_OBJECT
public signals:
void NameChanged(const QString & name);
void AddressChanged(const QString & address);
void BirthDateChanged(const QDate & date);
GETSET(QString, Name)
GETSET(QString, Address)
GETSET(QDate, BirthDate)
}
-
This code emits a
...Changed
signal every time the setter is called, while the Qt documentation (The Property System) clearly says: "The NOTIFY signal should only be emitted when the property has really been changed, to avoid bindings being unnecessarily re-evaluated in QML, for example."– tistolzSep 28, 2021 at 16:33 -
you could simply check if the value has changed before emiting the signal Sep 29, 2021 at 20:35