Please nominate your Qt Champions for 2021!

A "wholesome" QProperty

  • It's a common practice, define private data member, define public (or protected) data accessor (set/get methods).

    I've been looking at QProperty to help me reduce lines of code, but found out it requires me to write the set/get methods. Is there a more "wholesome" Qt Macro that would also provide the content of the simple "get/set" methods?

    I know, I can easily write one myself, just wanted to know if Qt already has it.

  • No, there is not.
    The point is, the get/set methods are needed by moc for creation of the meta object code.
    And moc does not do pre compiling.

    You have to write the getter and setter.

  • I think "this discussion": may interest you.

  • an easy way is define your own macro if you always have the same thing to do :

    #define commonMember(type,x)
    type m_ ## x
    type get ## x () { return m_ ## x;}
    void set ## x (type a){ m_## x = a;}

    From my point of view however, it tends to ugliness : I prefer to write my trivial getters on demand, if required (less code, less bug, less test)

    _Macro not compiled, not tested, so not working, it's just to give the spirit of it ;-) _

  • THis macro has one problem: It does not work with Q_PROPERTY, and that's what he asked for.
    For Q_PROPERTY it's currently not possible.

  • But you could use this macro in conjunction with Q_PROPERTY couldn't you? Or does moc try to be smart and actually complain if it can't find the getter/setter? I've not tried it.

  • We tried one combined macro, not two...
    It's wrth a try

  • Ok,

    I tried it out. This works (is compilable):

    #define commonMember(type,x)
    type m_ ## x;
    type get ## x () { return m_ ## x;}
    void set ## x (type a){ m_ ## x = a;}

    class MainWindow : public QMainWindow
    Q_PROPERTY(bool test READ gettest WRITE settest)

    commonMember(bool, test)



  • Is it still impossible to generate Q_PROPERTY from a macro?

  • Moderators

    "Qt 5.1 introduces": a new keyword for Q_PROPERTY:
    @New keyword in Q_PROPERTY: MEMBER let you bind a property to a class member without requiring to have a getter or a setter.@

Log in to reply