Qt World Summit: Register Today!

Property or manual variabile with setter+getter?

  • This could sound trivial, but when should I use a property in the case I need always a setter and a getter? I mean, if I'm not going to use metaobject protocol, which is the best approach?

  • Moved to General (Qt question), this is not for C++ gurus.

    A Q_PROPERTY always needs the getter, and probably the setter method(s). If you have them, you can make your attribute a property. If you don't need it in a metaobject, you don't need the property. On the other hand, it doesn't harm :-) Oh, and Q_PROPERTY needs your class to be based on QObject, of course.

  • A Q_PROPERTY can be seen as doing two things (IMHO):

    It adds a semantic meaning to a set of methods (a getter, and possibly a setter, a signal and/or a reset method). This tells the user of your API that these all belong together. It acts as a kind of documentation, which is a Good Thing(TM).

    It adds introspection capabilities for your property. The flags you can add to the property help at that task. This also makes it possible do things like

    myObject->setProperty("foo", someValue);

    I find the first to be the most important, though the second can bring real technical benefits as well, especially when you want to expose your classes to scripting, for D-BUS or to QML.

Log in to reply