31

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 4

51

Do a right click on your member then Refactor then Generate Getter and Setter member function and you're done :)

example


On Qt Creator 3.2.x, create the member, then click on it and press alt+Enter :

enter image description here

4
  • 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 ?
    – merours
    Nov 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 !
    – merours
    Nov 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
    – Kahn
    Oct 29, 2014 at 11:04
21

Position your text cursor at the member variable in class definition, then hit Alt+Enter.

1
  • This doesn't work for me, running Qt Creator under Ubuntu 14 in a VirtualBox. Apr 27, 2018 at 13:48
0

For me, right-click, Refactor, Create Getter and Setter member functions works, except when the member is a bool.

1
  • i guess it is not very convenient when you change the property name Sep 29, 2021 at 21:05
0

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)
}
2
  • 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."
    – tistolz
    Sep 28, 2021 at 16:33
  • you could simply check if the value has changed before emiting the signal Sep 29, 2021 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.